如何访问 class' 属性而不是对象

how to access class' attribute instead of objects

假设你有

class c:
    pass
print(c.__call__)

output: <method-wrapper '__call__' of type object at 0x0000023378F28DC8>

我的问题是,如果定义了 __call__,我将无法获得相同的输出
像这样:

class c:
    __call__ = lambda self: None
print(c.__call__)

output: <function c.<lambda> at 0x000002337A069B70>

而且 type.__getattribute__(c, '__call__') 都不起作用

总而言之,我想要两个示例中的第一个输出
有可能吗(我想通过一些元编程)

这与 class 变量和同名实例变量可能遇到的问题相同:

class Test:
    var = 1             # class variable

    def __init__(self):
        self.var = 2    # instance variable with the same name

t = Test()
print(t.var)     # prints 2, the instance variable, not the class variable
print(Test.var)  # prints 1, the class variable

在您的第一个示例中,__call__ 方法在元class、type 中定义。您正在通过 type、class c 的实例访问它。如果你在c中定义了一个class变量,它在metaclass透视中本质上是一个实例变量,所以你看不到任何在metaclass中定义的版本更多

如我上面的class变量代码,从metaclass中获取__call__方法的最佳方式是直接命名:type.__call__。如果您认为您可能有其他元class,您可以在class 上调用type,以获取元class 而无需命名:type(c).__call__

请注意,type.__call__ 方法在不同情况下获得 运行 与正常 class 中定义的 __call__ 方法不同。当您调用 class 时,解释器 运行s type.__call__,例如c(),而 c.__call__ 在调用实例时得到 运行:

obj = c()  # this is type.__call__
obj()      # this is where c.__call__ runs