简体   繁体   English

为什么元类的__call__方法调用类,而本机类的__call__不是呢?

[英]Why metaclass's __call__ method called on class, but native class's __call__ not?

class Meta(type):
    def __call__(cls, *args, **kwargs):
        print 'Meta.__call__ called.'
        return super(Meta, cls).__call__(*args, **kwargs)


class MetaInstance(object):
    __metaclass__ = Meta

# Instantiate class.
MetaInstance()  # Meta.__call__ called.


class StandardClass(object):
    @classmethod
    def __call__(cls, *args, **kwargs):
        print 'StandardClass.__call__ called.'
        return super(StandardClass, cls).__call__(*args, **kwargs)

# Instantiate class.
StandardClass()  # StandardClass.__call__ is not called!

Why metaclass's __call__ method called on class, but native class's __call__ not, when i instantiate a class? 当实例化一个类时,为什么元类的__call__方法调用类,而本机类的__call__没有__call__

When you create a class instance, the metaclass's (whose instance the class is) __call__ is called. 创建类实例时,将__call__元类的(实例是该类的) __call__

# Instantiate class.
StandardClass()  # StandardClass.__call__ is not called!

When you create a class instance and then "call" the instance, then the class's __call__ is called. 当您创建一个类实例然后“调用”该实例时,该类的__call__被调用。 I don't think decorating __call__ with classmethod will work though. 我认为用classmethod装饰__call__不会起作用。

This will call your metaclass's and class's __call__ s: 这将调用您的元类和类的__call__

StandardClass()()

Because magic methods are looked up on the class . 因为魔术方法是在课堂上查找的 In other words, when you write a __call__ method on a class, it defines what happens when you call an instance of that class, not what happens when you call the class itself. 换句话说,当您在类上编写__call__方法时,它定义了在调用该类的实例时发生的情况 ,而不是在调用类本身时发生的情况。 A class is an instance of its metaclass, so defining __call__ on the metaclass defines what happens when you call the class. 类是其元类的实例,因此在元类上定义__call__定义了调用该类时发生的情况。

You can already see in your example that you're not doing the same thing in the two cases. 您已经在示例中看到,在两种情况下您没有做相同的事情。 For the metaclass example, you defined two things, a metaclass and a "meta-instance" (ie, a regular class), and you called the second one. 对于元类示例,您定义了两件事,一个元类和一个“元实例”(即常规类),然后您调用了第二个。 For the second example, you only defined one thing (a class). 对于第二个示例,您仅定义了一件事(一个类)。 To be parallel to the first example, you would need to create an instance of StandardClass and then call that, in which case StandardClass.__call__ will be called. 与第一个示例平行,您需要创建一个StandardClass 实例 ,然后调用该实例 ,在这种情况下将调用StandardClass.__call__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM