How do I call a parent class's method from a child class in Python? How do I call a parent class's method from a child class in Python? python python

How do I call a parent class's method from a child class in Python?


Use the super() function:

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:

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

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.

Example:

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()


ImmediateParentClass.frotz(self)

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 whatever in 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!


matomo