Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #33638 > unrolled thread
| Started by | Marco <name.surname@gmail.com> |
|---|---|
| First post | 2012-11-20 18:29 +0100 |
| Last post | 2012-11-20 12:25 -0700 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
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
| From | Marco <name.surname@gmail.com> |
|---|---|
| Date | 2012-11-20 18:29 +0100 |
| Subject | The 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]
| From | Ian Kelly <ian.g.kelly@gmail.com> |
|---|---|
| Date | 2012-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