【发布时间】:2018-01-14 03:37:22
【问题描述】:
据我了解,类内部的__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__ 方法被调用的。这是如何工作的?
【问题讨论】:
标签: python class metaprogramming metaclass