先看一段代码,
str.__call__("ADSDD")
list.__call__("asdsad")
dict.__call__(a=10)
class A:
def __init__(self, x):
self.x = x
A.__call__(10)
结果依次为:
'ADSDD'
['a', 's', 'd', 's', 'a', 'd']
{'a': 10}
<__main__.A at 0x22adf1211f0>
从输出我们可以发现,python所有类(type)对象的元类的__call__方法默认都被定义为创建对象,即为:
class Meta(type):
def __call__(cls, *args, **kwargs):
obj = object.__new__(cls)
obj.__init__(*args, **kwargs)
return obj
class A(metaclass=Meta):
def __init__(self, x):
self.x = x
测试代码:
class Meta(type):
def __call__(cls, *args, **kwargs):
obj = object.__new__(cls)
obj.__init__(*args, **kwargs)
print("Meta __call__")
return obj
class A(metaclass=Meta):
def __init__(self, x):
self.x = x
a = A(10)
a.x
输出结果:
Meta __call__
10