Ankur Agarwal
Ankur Agarwal

Reputation: 24768

Python super usage example

Python docs for super say: Return a proxy object that delegates method calls to a parent or sibling class of type

super(type[, object-or-type])

http://docs.python.org/2/library/functions.html#super

Can someone give me a super example where method calls are delegated to sibling class of type?

Upvotes: 2

Views: 485

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

When using a triangle inheritence pattern:

>>> class A(object):
...     def __init__(self):
...         print 'A.__init__()'
...         super(A, self).__init__()
... 
>>> class B(object):
...     def __init__(self):
...         print 'B.__init__()'
...         super(B, self).__init__()
... 
>>> class C(A, B):
...     def __init__(self):
...         print 'C.__init__()'
...         super(C, self).__init__()
... 
>>> C()
C.__init__()
A.__init__()
B.__init__()
<__main__.C object at 0x10f27e190>

Here super(A, self).__init__() inside of A.__init__() called B.__init__(), a sibling class.

super() looks at the classes in the MRO (method resolution order) on self, locates where the first argument is located in that order, and returns the requested method on the next class after that. For C, the MRO is:

>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)

so super(A, self) looks for methods on B and on object.

Upvotes: 7

Related Questions