I have just learned that super()
allows you to call a method in a base class from within the overridden method in a subclass. But can you please explain to me with a good example?
Asked
Active
Viewed 93 times
0

Daniel
- 19,179
- 7
- 60
- 74

James Sapam
- 16,036
- 12
- 50
- 73
-
2http://rhettinger.wordpress.com/2011/05/26/super-considered-super/ – user2357112 Sep 01 '13 at 12:24
-
possible duplicate of [How does Python's "super" do the right thing?](http://stackoverflow.com/questions/607186/how-does-pythons-super-do-the-right-thing) – Ashwini Chaudhary Sep 01 '13 at 12:43
-
I'm afraid the "how does it do it" part is typically irrelevant for beginners trying to understand just the "how can I use it" part; but of course it doesn't hurt to mention it either! – Erik Kaplun Sep 14 '13 at 15:57
1 Answers
1
Normally you can just call parent class methods directly by doing Parent.foo(self, ...)
, but in case of multiple inheritance, super()
is much more useful; also, even with single inheritance, super()
helps you by not forcing you to hardcode the parent class into the child class, so if you change it, calls using super()
will just continue working.
class Base(object):
def foo(self):
print 'Base'
class Child1(Base):
def foo(self):
super(Child1, self).foo()
print 'Child1'
class Child2(Base):
def foo(self):
super(Child2, self).foo()
print 'Child2'
class GrandChild(Child1, Child2):
def foo(self):
super(Child2, self).foo()
print 'GrandChild'
Base().foo()
# outputs:
# Base
Child1().foo()
# outputs:
# Base
# Child1
Child2().foo()
# outputs:
# Base
# Child2
GrandChild().foo()
# outputs:
# Base
# Child1
# Child2
# GrandChild
You can find out more in the documentation, and by googling "diamond inheritance" or "diamond inheritance python".

Erik Kaplun
- 37,128
- 15
- 99
- 111
-
Thanks it gave me good ideas, and could you help me in understanding with __init__() at the inherited classes. – James Sapam Sep 14 '13 at 05:16
-
1`__init__` works just like any other method with regards with inheritance—you also have to explicitly call the superclass `__init__` either using `super(...)` or not... also, please accept my answer if it answered your question or at least you found it useful! :) – Erik Kaplun Sep 14 '13 at 15:53