类的特殊(高级)成员方法
1.__doc__ 表示类的描述信息
class student(object):
"这个类是描述学生信息的"
def __init__(self,name,age):
self.name=name
self.age=age
print("--Name is %s,Age is %s"%(self.name,self.age))
s1=student("Lily",25)
print(student.__doc__)
运行结果:
--Name is Lily,Age is 25 这个类是描述学生信息的
2. .__init__ 构造方法,通过类创建对象时,自动触发执行。
__del__ 析构方法,当对象在内存中被释放时,自动触发执行
__module__ : 输出当前实例所用的类是从哪个模块导入的
__class__ : 输出当前实例所用的类
class C:
def __init__(self):
self.name = 'wupeiqi'
from lib.aa import C obj = C() print(obj.__module__) # 输出 lib.aa,即:输出模块 print(obj.__class__) # 输出 lib.aa.C,即:输出类
3. __call__ : 对象后面加括号,触发执行。
(注:构造方法的执行时由创建对象触发的,即:对象=类名();
而对于__call__方法的执行是由对象后加括号触发的,即: 对象()或者类()())
class student(object):
def __init__(self,name):
self.name=name
def __call__(self,*args,**kwargs):
print("running call",args,kwargs)
s1=student("Lily")
s1()
student("Lily")()
s1(1,2,3,name="Lily")
运行结果:
running call () {}
running call () {}
running call (1, 2, 3) {'name': 'Lily'}
4. __dict__ 查看类或对象中的所有成员
class student(object):
def __init__(self,name,age):
self.name=name
self.age=age
print("--Name is %s,Age is %s"%(self.name,self.age))
def __call__(self,*args,**kwargs):
print("running call",args,kwargs)
s1=student("Lily",25)
s1(1,2,3,name="Lily")
print(student.__dict__) #打印类里的所有属性,不包括实例属性
print(s1.__dict__) #打印所有实例属性,不包括类属性
运行结果:
--Name is Lily,Age is 25
running call (1, 2, 3) {'name': 'Lily'}
{'__init__': <function student.__init__ at 0x00000000007E4488>, '__weakref__': <attribute '__weakref__' of 'student' objects>, '__dict__': <attribute '__dict__' of 'student' objects>, '__module__': '__main__', '__doc__': None, '__call__': <function student.__call__ at 0x00000000007E4598>}
{'name': 'Lily', 'age': 25}
4. __str__ 如果一个类中定义了__str__方法,那么在打印对象的时候,默认输出该方法的返回值。
直接打印实例名的话,打印出来的是方法的的内存地址。
加上__str__(self)以后,打印出来的就是具体的返回值了。
class student(object):
def __init__(self,name):
self.name=name
s1=student("Lily")
print(s1)
s2=student("Lucy")
print(s2)
运行结果:
<__main__.student object at 0x0000000000C62FD0>
<__main__.student object at 0x0000000000C62BE0>
class student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return "obj is %s"%self.name
s1=student("Lily")
print(s1)
运行结果:
obj is Lily
5. __getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分别表示获取、设置、删除数据。把实例变成了一个字典。
class Foo(object): #key键-value值
def __init__(self):
self.data={}
def __getitem__(self, key):
print('__getitem__', key)
return self.data.get(key)
def __setitem__(self, key, value):
print('__setitem__', key, value)
self.data[key]=value
def __delitem__(self, key):
print('__delitem__', key)
obj = Foo()
obj['age']=19 # 自动触发执行 __setitem__
print(obj['age']) #自动触发执行 __getitem__
print(obj.data)
del obj["age"] #自动触发执行 __delitem__
运行结果:
__setitem__ age 19
__getitem__ age
19
{'age': 19}
__delitem__ age
浙公网安备 33010602011771号