我想知道为什么当我将函数声明为类方法时,类中的 call 方法不起作用。 这是一个例子:
class Foo:
bar = 0
@classmethod
def __call__(cls):
print(cls.bar)
当我使用 Foo() 时,它不会打印出 bar。为什么?
@classmethod
不会改变 when 方法查找会找到一个方法。它只会改变找到方法时绑定的参数。
将 @classmethod
放在
__call__
上意味着如果您调用
Foo
类的实例:
foo = Foo() # not here
foo() # here
__call__
的第一个参数将是类,而不是实例。将
@classmethod
放在
__call__
上将not 意味着该方法将用于调用
Foo
本身。当查找实现语言功能的魔术方法时,Python 在几乎所有情况下都会绕过普通的方法查找过程,并通过对象的类的 MRO 执行直接搜索。对于调用
Foo()
,对象是
Foo
本身,其类是
type
,因此
__call__
查找找到
type.__call__
,绕过直接在
Foo
上定义的任何内容。