在python3中有个很多python自定义的类的特殊成员方法。下面我们一一学来
__doc__
__init__
__module__ 和 __class__
__del__
__call__
__dict__
__str__
__getitem__、__setitem__、__delitem__
__doc__
表示类的描述信息
class Demo(object):
"""
我是一个描述,我可以通过__doc__来调用
"""
def func(self):
pass
demo = Demo
print(demo.__doc__) # 我是一个描述,我可以通过__doc__来调用
__init__
构造方法,通过类创建对象时,自动触发执行。
class DemoSpecial(object):
def __init__(self):
print("i am GPF")
demo = DemoSpecial() # i am GPF
__module__ 和 __class__
#ClassDemo包下创建一个Demo.py
class DemoSpecial(object):
def __init__(self):
print("i am GPF")
#ClassDemo包下创建一个DemoSpecial.py
from ClassDemo.Demo import DemoSpecial
demo = DemoSpecial()
print("__module__",demo.__module__) #__module__ ClassDemo.Demo 即:输出模块
print("__class__",demo.__class__) #__class__ <class 'ClassDemo.Demo.DemoSpecial'> 即:输出类
__del__
析构方法,当对象在内存中被释放时,自动触发执行。
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的
__call__
对象后面加括号,触发执行。
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Demo2:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__','is running...')
demo2 = Demo2() # 执行 __init__
demo2() # 执行 __call__ #__call__ is running...
__dict__
查看类或对象中的所有成员
class Demo3:
author = 'GPF'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print('func')
# 获取类的成员,即:静态字段、方法、
print(Demo3.__dict__)
# {'__init__': <function Demo3.__init__ at 0x000002680D43F6A8>, '__dict__': <attribute '__dict__' of 'Demo3' objects>, 'func': <function Demo3.func at 0x000002680D43F730>, 'author': 'GPF', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Demo3' objects>, '__doc__': None}
demo3 = Demo3('xima', 10000)
print(demo3.__dict__)
# 获取 对象 demo3 的成员
# 输出:{'count': 10000, 'name': 'xima'}
demo31 = Demo3('jj', 5222)
print(demo31.__dict__)
# 获取 对象 demo31 的成员
# 输出:{'count': 5222, 'name': 'jj'}
__str__
__str__
如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
class Demo4(object):
def __str__(self):
return 'this is Str func'
demo4 = Demo4()
print(demo4) #this is Str func
__getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分别表示获取、设置、删除数据
class Demo5(object):
def __getitem__(self, key):
print('__getitem__',key)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem__',key)
demo5 = Demo5()
result = demo5['k1'] # 自动触发执行 __getitem__
demo5['k2'] = 'GPF' # 自动触发执行 __setitem__
del demo5['k1']