Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #33638 > unrolled thread

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

Started byMarco <name.surname@gmail.com>
First post2012-11-20 18:29 +0100
Last post2012-11-20 12:25 -0700
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  The type.__call__() method manages the calls to __new__ and __init__? Marco <name.surname@gmail.com> - 2012-11-20 18:29 +0100
    Re: The type.__call__() method manages the calls to __new__ and __init__? Ian Kelly <ian.g.kelly@gmail.com> - 2012-11-20 12:25 -0700

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

FromMarco <name.surname@gmail.com>
Date2012-11-20 18:29 +0100
SubjectThe type.__call__() method manages the calls to __new__ and __init__?
Message-ID<k8gekt$n48$1@speranza.aioe.org>
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:

 >>> class Foo:
...     def __new__(cls):
...         print('Foo.__new__()')
...         return super().__new__(cls)
...     def __init__(self):
...         print('Foo.__init__(self)')
...
 >>> f = type.__call__(Foo)
Foo.__new__()
Foo.__init__(self)

Is that right? Thanks in advance


-- 
Marco

[toc] | [next] | [standalone]


#33647

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-11-20 12:25 -0700
Message-ID<mailman.80.1353439541.29569.python-list@python.org>
In reply to#33638
On Tue, Nov 20, 2012 at 10:29 AM, Marco <name.surname@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>

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web