据我理解,类中的__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 Cookbook,作者定义了一个元类来控制实例的创建,以便您不能直接实例化一个对象。他是这样做的:
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__
方法却被调用了。这是如何工作的?
type.__call__
的实现实际上是神奇的 - 它根据第一个参数/调用者的不同而表现出不同的行为!) - BadZen