标签:
1.静态方法(用得少)(解除某个函数跟类的关联,加了静态方法后,类便不能将类的参数传给静态方法函数了)
class Dog(object):
def __init__(self,name):
@staticmethod #下边的函数就是静态方法,但是下边的eat函数跟Dog类没有关联了,只是调用eat的时候,需要实例化Dog类再调用,eat不能再调用Dog类的任何参数和函数了
def eat(self,food):
print("%s is eating %s " %(self.name,food))
2.类方法(用得少)
class Dog(object):
name = "wt"
def __init__(self,name):
pass
@classmethod #下边的函数就是类方法,但是类方法只能调用类变量,不能调用实例化的时候传的新参数
def eat(self,food):
print("%s is eating %s " %(self.name,food))
3.属性方法(用得少)
class Dog(object):
name = "wt"
def __init__(self,name):
pass
@property#将下边的函数变为属性,调用该函数的时候,该函数不用加括号了。
def eat(self):
print("%s is eating %s " %(self.name)
调用:
e = Dog
e.eat
给eat函数赋值
class Dog(object):
def __init__(self,name):
self.name = name
self.__food = None
@property#将下边的函数变为属性,调用该函数的时候,该函数不用加括号了。
def eat(self):
print("%s is eating %s " %(self.name)
@eat.setter #给属性函数赋值或修改赋值,必须创建一个函数
def eat(self,food):
self .__food = food
@eat.deleter #删除属性变量
def eat(self):
del self.__food
调用:
e = Dog
e.eat = "包子"#给属性函数赋值
e.eat
4.__doc__打印类的描述信息
obj.__module__ 查看当前操作对象obj是在哪个模块中
obj.__class__ 查看当前操作的对象obj的类是什么
5. __call__ 对象后面加括号,触发执行。
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象名() 或者 类名()()来执行__call__方法。
6.__dict__
类.__dict__:打印类的所有函数和变量
实例.__dict__:查看实例的所有属性
用于索引操作,如字典。以上分别表示获取、设置、删除数据
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Foo(object): def __getitem__(self, key): print(‘__getitem__‘,key) def __setitem__(self, key, value): print(‘__setitem__‘,key,value) def __delitem__(self, key): print(‘__delitem__‘,key)obj = Foo()result = obj[‘k1‘] # 自动触发执行 __getitem__obj[‘k2‘] = ‘alex‘ # 自动触发执行 __setitem__del obj[‘k1‘] |
8.创建类就可以有两种方式:
a). 普通方式
|
1
2
3
4
|
class Foo(object): def func(self): print ‘hello alex‘ |
b). 特殊方式
|
1
2
3
4
5
6
7
|
def func(self): print ‘hello wupeiqi‘ Foo = type(‘Foo‘,(object,), {‘func‘: func})#type第一个参数:类名#type第二个参数:当前类的基类#type第三个参数:类的成员 |
将两个函数合成一个类:
def func(self):
print("hello %s"%self.name)
def __init__(self,name,age):
self.name = name
self.age = age
Foo = type(‘Foo‘,(object,),{‘func‘:func,‘__init__‘:__init__})
f = Foo("jack",22)
f.func()
So ,孩子记住,类 是由 type 类实例化产生
那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。
11.__new__():创建新实例
__init__():初始化实例
class MyType(type): def __init__(self, what, bases=None, dict=None): print("--MyType init---") super(MyType, self).__init__(what, bases, dict) def __call__(self, *args, **kwargs): print("--MyType call---") obj = self.__new__(self, *args, **kwargs) self.__init__(obj, *args, **kwargs)class Foo(object): __metaclass__ = MyType def __init__(self, name): self.name = name print("Foo ---init__") def __new__(cls, *args, **kwargs): #这里的cls是Foo print("Foo --new--") return object.__new__(cls)# 第一阶段:解释器从上到下执行代码创建Foo类# 第二阶段:通过Foo类创建obj对象obj = Foo("Alex")
12.反射:通过字符串来映射内存中的对象,银狐用户输入的是字符串,通过这种方法来修改程序运行时的状态、属性、方法, 有以下4个方法:
class Foo(object):
def __init__(self):
self.name = ‘wupeiqi‘
def func(self):
print ("haha")
obj = Foo()
# #### 检查一个对象里是否含有对应的函数 ####
hasattr(obj, ‘name‘)#检查对象obj里是否还有变量name,有则返回True
hasattr(obj, ‘func‘)
# #### 获取成员 ####
getattr(obj, ‘name‘)
getattr(obj, ‘func‘)#返回函数func的内存地址,加括号运行函数
getattr(obj,‘func‘)()执行该函数
# #### 设置成员 ####
在类的外边定义一个函数hello
def hello():
print("hello")
setattr(obj, ‘age‘, 18)#格式:(实例名,变量名,值) 修改age的值为18
setattr(obj, ‘func‘, hello)#将func函数替换为hello函数
obj.func()#执行func函数,obj为类的实例
输出:hello,而不是原来的haha
# #### 删除成员 ####
delattr(obj, ‘name‘)#删除实例的name变量,用hasattr(obj, ‘name‘)测试发现,返回False,说明‘name’已经被删除
delattr(obj, ‘func‘)#删除实例的func函数
13.异常处理:
try:
pass
except Exception as e:#(python3里是as 不知道是什么类型错误的时候用Exception)
print e# e是错误的详细信息
常用异常类型:
AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常;基本上是无法打开文件 ImportError 无法引入模块或包;基本上是路径问题或名称错误 IndentationError 语法错误(的子类) ;代码没有正确对齐 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] KeyError 试图访问字典里不存在的键 KeyboardInterrupt Ctrl+C被按下 NameError 使用一个还未被赋予对象的变量 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了) TypeError 传入对象类型与要求的不符合 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 导致你以为正在访问它 ValueError 传入一个调用者不期望的值,即使值的类型是正确的
14.
try:
pass
except:
pass
finally:
print("ddd")#执行完try或except后,都要执行finally
15.自定义异常
class WupeiqiException (Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.messagetry: raise WupeiqiException(‘自定义语句我的异常‘) #raise主动触发异常except WupeiqiException as e: print (e)
16.socket通信
服务端:
import socket
server = socket.socket()
server.bind((‘localhost‘,6666))
server.listen(1)
print("我在等。。。")
conn, addr = server.accept()
print(conn,addr)
print("电话来了!")
data = conn.recv(1024)
print("recv:", data.decode())
conn.send(data.upper())
server.close()
输出:
我在等。。。
<socket.socket object, fd=564, family=2, type=1, proto=0> (‘127.0.0.1‘, 56397)
电话来了!
recv: b‘hello world‘
客户端:
import socket
client = socket.socket()
client.connect((‘localhost‘,6666))
client.send(‘你好‘.encode(‘utf-8‘))
data = client.recv(1024)
print("recv:", data)
client.close()
输出:recv: b‘HELLO WORLD‘
标签:
原文地址:http://www.cnblogs.com/wt11/p/5837885.html