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

M

Marco

Looking at the documentation of Py3.3:

http://docs.python.org/3.3/reference/datamodel.html#object.__new__

I saw the method `__new__()` is called automatically when I create an
istance. After the call to __new__(), if it returns an instance `self`
then `self.__init__()` is called.

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:
.... def __new__(cls):
.... print('Foo.__new__()')
.... return super().__new__(cls)
.... def __init__(self):
.... print('Foo.__init__(self)')
....Foo.__new__()
Foo.__init__(self)

Is that right? Thanks in advance
 
I

Ian Kelly

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:
.... def __call__(cls):
.... print("before")
.... self = super().__call__()
.... print("after", self)
.... return self
........ def __new__(cls):
.... print("__new__")
.... return super().__new__(cls)
.... def __init__(self):
.... print("__init__")
....before
__new__
__init__
after <__main__.Foo object at 0x00C55410>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top