据我了解__call__
类中的方法实现了函数调用运算符,例如:
class Foo:
def __init__(self):
print("I'm inside the __init__ method")
def __call__(self):
print("I'm inside the __call__ method")
x = Foo() #outputs "I'm inside the __init__ method"
x() #outputs "I'm inside the __call__ method"
然而,我正在经历Python 食谱并且作者定义了一个元类来控制实例创建,这样你就不能直接实例化对象。他是这样做的:
class NoInstance(type):
def __call__(self, *args, **kwargs):
raise TypeError("Can't instantaite class directly")
class Spam(metaclass=NoInstance):
@staticmethod
def grok(x):
print("Spam.grok")
Spam.grok(42) #outputs "Spam.grok"
s = Spam() #outputs TypeError: Can't instantaite class directly
然而,我不明白的是如何s()
没有被调用,但它是__call__
方法被调用。这是如何运作的?
元类实现类(而不是实例)的行为方式。因此,当您查看实例创建时:
x = Foo()
这实际上是“调用”该类Foo
。这就是为什么__call__
元类的调用之前__new__
and __init__
类的方法初始化实例。
正如 @Take_Care_ 在评论中指出的,元类的一项重要资源是ionelmc 的博客文章关于“理解Python元类”。该博文中的一张图片直接适用于您的情况:
图片是直接从博文中复制过来的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)