This question already has an answer here:
need to understand the flow of __init__, __new__ and __call__
(1个答案)
3年前关闭。
据我了解,类内部的
但是,我正在遍历Python Cookbook,作者定义了一个元类来控制实例的创建,因此您不能直接实例化一个对象。这是他的做法:
但是,我没有得到的是如何不调用
这实际上是“调用”类
正如@Take_Care_在评论中指出的那样,关于元类的一个重要资源是关于“了解Python元类”的ionelmc's blog post。该博客文章中的一张图片直接适用于您的情况:
该图像直接从博客文章中复制。
(1个答案)
3年前关闭。
据我了解,类内部的
__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__
方法。这是如何运作的? 最佳答案
元类实现类的行为方式(而不是实例)。因此,当您查看实例创建时:
x = Foo()
这实际上是“调用”类
Foo
。这就是为什么在类的__call__
和__new__
方法初始化实例之前调用元类的__init__
的原因。正如@Take_Care_在评论中指出的那样,关于元类的一个重要资源是关于“了解Python元类”的ionelmc's blog post。该博客文章中的一张图片直接适用于您的情况:
该图像直接从博客文章中复制。
09-13 00:02