day25
__init__ 类()自动执行
__del__
__call__ 对象() 类()() 自动执行
__int__ int(对象)
__str__ str()
特殊成员
1 class Foo: 2 def __init__(self): 3 print('init') 4 5 def __call__(self, *argc, **kwarge): 6 print('call') 7 8 obj = Foo()#直接执行__init__ 9 10 obj()#执行__call__中内容 11 12 Foo()()#同上
对象加括号,obj()执行__call__()。
执行结果:
init
call
init
call
Process finished with exit code 0
__str__,__int__
1 class Foo: 2 def __init__(self): 3 pass 4 5 def __int__(self): 6 return 111 7 8 def __str__(self): 9 return "nizhipeng" 10 obj = Foo() 11 12 print(obj, type(obj)) 13 14 r = int(obj)#自动执行__int__方法,并将返回值给int对象 15 print(r) 16 17 print(str(obj))
类型转换的时候,自动执行__int__,和__str__方法。
执行结果:
nizhipeng <class '__main__.Foo'> 111 nizhipeng Process finished with exit code 0
自动转换
1 class Foo: 2 def __init__(self, n, a): 3 self.name = n 4 self.age = a 5 def __str__(self): 6 return '%s-%s' %(self.name, self.age) 7 8 obj = Foo('alex', 18) 9 print(obj) #obj自动转成了str类型
第9行自动执行了str(obj)。
执行结果:
alex-18
Process finished with exit code 0