Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #10958 > unrolled thread
| Started by | Eli Bendersky <eliben@gmail.com> |
|---|---|
| First post | 2011-08-06 10:34 +0300 |
| Last post | 2011-08-06 10:11 +0200 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
Calling super() in __init__ of a metaclass Eli Bendersky <eliben@gmail.com> - 2011-08-06 10:34 +0300
Re: Calling super() in __init__ of a metaclass Peter Otten <__peter__@web.de> - 2011-08-06 10:11 +0200
| From | Eli Bendersky <eliben@gmail.com> |
|---|---|
| Date | 2011-08-06 10:34 +0300 |
| Subject | Calling super() in __init__ of a metaclass |
| Message-ID | <mailman.1962.1312616111.1164.python-list@python.org> |
Consider this standard metaclass definition:
class MyMetaclass(type):
def __init__(cls, name, bases, dct):
super(MyMetaclass, cls).__init__(name, bases, dct)
# do meta-stuff
class Foo(object):
__metaclass__ = MyMetaclass
The call "super(MyMetaclass, cls)" should returns the parent of
MyMetaclass here. But the 'cls' passed into this __init__ is *not*
MyMetaclass, but rather the created class - i.e. Foo. So how does
"super" get to the parent of MyMetaclass using this information? The
documentation of "super" says:
If the second argument is a type, issubclass(type2, type) must be
true (this is useful for classmethods).
Yes, 'cls' is a type (it's "class Foo"), but no, it's not a subclass
of MyMetaclass, so this doesn't help.
Eli
[toc] | [next] | [standalone]
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2011-08-06 10:11 +0200 |
| Message-ID | <j1isvp$4v3$1@solani.org> |
| In reply to | #10958 |
Eli Bendersky wrote:
> Consider this standard metaclass definition:
>
> class MyMetaclass(type):
> def __init__(cls, name, bases, dct):
> super(MyMetaclass, cls).__init__(name, bases, dct)
> # do meta-stuff
>
> class Foo(object):
> __metaclass__ = MyMetaclass
>
> The call "super(MyMetaclass, cls)" should returns the parent of
> MyMetaclass here. But the 'cls' passed into this __init__ is *not*
> MyMetaclass, but rather the created class - i.e. Foo. So how does
> "super" get to the parent of MyMetaclass using this information? The
> documentation of "super" says:
>
> If the second argument is a type, issubclass(type2, type) must be
> true (this is useful for classmethods).
>
> Yes, 'cls' is a type (it's "class Foo"), but no, it's not a subclass
> of MyMetaclass, so this doesn't help.
Don't let yourself get confused by the name 'cls' for what is normally
called 'self'. Foo is an instance of MyMetaclass, so the situation is
exactly the same as in
class A(object):
def __init__(self, ...)
super(A, self).__init__(...)
I don't know how exactly super() is implemented, but to go from an instance
to its class you can use type(instance) or instance.__class__.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web