__call__
- 对象后面加括号调用时,会自动触发执行
- 注:构造方法的执行是由创建对象触发的,即:对象=类名();而对于__call__方法的执行是由对象后加括号触发的,即:对象()或者类()()
class Foo:
def __init__(self, name, age):
print('from init')
def __call__(self, *args, **kwargs):
print(self, args, kwargs)
obj = Foo('nick', 18) # 实例化对象时触发__init__
from init
obj(1,2,3,a=1,b=2) # 对象加括号调用时触发__call__
<__main__.Foo object at 0x00000265C74DA0F0> (1, 2, 3) {'a': 1, 'b': 2}
__str__
class Foo:
def __init__(self):
print('from init')
def __str__(self):
return 'from str' # 以字符串类型返回值传给打印,
obj = Foo()
from init
print(obj)
from str
__del__
class Foo:
def __init__(self):
print('from init')
def __del__(self):
print('from del')
obj = Foo()
from init
del obj
from del