0

Given the following example on an instance of a X class:

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? Example:

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

Calling directly, as if passing to __init__. But, before it calls __call__ that calls __new__ that passes the arguments to __init__. How can I access that "metaclass __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)])
glglgl
  • 89,107
  • 13
  • 149
  • 217
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114

1 Answers1

1

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__.

But I am sure that you don't need that and that you just want __init__.

glglgl
  • 89,107
  • 13
  • 149
  • 217