How do I call a parent class's method from a child class in Python?
class Foo(Bar): def baz(self, arg): return super().baz(arg)
For Python < 3, you must explicitly opt in to using new-style classes and use:
class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg)
Python also has super as well:
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
class A(object): # deriving from 'object' declares A as a 'new-style-class' def foo(self): print "foo"class B(A): def foo(self): super(B, self).foo() # calls 'A.foo()'myB = B()myB.foo()
will be just fine, whether the immediate parent class defined
frotz itself or inherited it.
super is only needed for proper support of multiple inheritance (and then it only works if every class uses it properly). In general,
AnyClass.whatever is going to look up
AnyClass's ancestors if
AnyClass doesn't define/override it, and this holds true for "child class calling parent's method" as for any other occurrence!