The type.__call__() method manages the calls to __new__ and __init__?

Ian Kelly ian.g.kelly at gmail.com
Tue Nov 20 20:25:08 CET 2012


On Tue, Nov 20, 2012 at 10:29 AM, Marco <name.surname at gmail.com> wrote:
> Because when I call an instance the __call__ method is called, and because
> the classes are instances of type, I thought when I call a Foo class this
> imply the call type.__call__(Foo), and so this one manages the Foo.__new__
> and Foo.__init__ calls:

Yes, that's right.  Observe:

>>> class MetaFoo(type):
...     def __call__(cls):
...         print("before")
...         self = super().__call__()
...         print("after", self)
...         return self
...
>>> class Foo(metaclass=MetaFoo):
...     def __new__(cls):
...         print("__new__")
...         return super().__new__(cls)
...     def __init__(self):
...         print("__init__")
...
>>> f = Foo()
before
__new__
__init__
after <__main__.Foo object at 0x00C55410>


More information about the Python-list mailing list