简体   繁体   English

我如何称呼元类的__call__?

[英]How can I call the metaclass's __call__?

Given the following example on an instance of a X class: 给定以下有关X类实例的示例:

class X():

    def __call__(self, incoming_list):
        print incoming_list

X()([x for x in range(10)])

How can I obtain the same output by using the __call__ magic method from the class itself instead of the instance? 如何通过使用类本身的__call__ magic方法而不是实例来获得相同的输出? Example: 例:

X([x for x in range(10)]) 

Calling directly, as if passing to __init__ . 直接调用,就像传递给__init__ But, before it calls __call__ that calls __new__ that passes the arguments to __init__ . 但是,在调用__call__之前,该调用将调用__new__并将参数传递给__init__ How can I access that "metaclass __call__ " ? 如何访问“元类__call__ ”? Is it possible? 可能吗?

Just to make it easier to understand, this gives me the same output from up there: 只是为了使其更容易理解,这给了我相同的输出:

class X:

    def __call__(self, incoming_list):
        print incoming_list

X().__call__([x for x in range(10)])

I want something like this: 我想要这样的东西:

class X:

    def X.__call__(incoming_list): # Syntax Error
        print incoming_list

X.__call__([x for x in range(10)])

I think you think too complicated. 我认为您认为太复杂了。

Probably you want something like 可能您想要类似

class X:
    def __init__(self, incoming_list):
        self.data = incoming_list # to keep them for later, if needed
        print incoming_list

X([x for x in range(10)])

Everything without a meta class, just on definition of the class. 没有元类的所有内容,仅取决于类的定义。

If you need a meta class, you can do it like 如果您需要元类,则可以像

class MC(type):
    def __call__(self, *a, **k):
    super(MC, self).__call
        print a, k
        r = super(MC, self).__call__(*a, **k)
        print "R", r
        return r

class X(object):
    __metaclass__ = MC
    def __init__(self, x): print "Init", x

Using it with 与它一起使用

>>> X(1)
(1,) {}
Init 1
R <__main__.X object at 0x00000000022907B8>
<__main__.X object at 0x00000000022907B8>

shows that the meta- __call__ is called, which, in turn, calls __init__ . 显示了__call__的元,该元又调用了__init__

But I am sure that you don't need that and that you just want __init__ . 但我确定您不需要,只需要__init__

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

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