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

769,552

Solution 1

Use the super() function:

class Foo(Bar):
    def baz(self, **kwargs):
        return super().baz(**kwargs)

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)

Solution 2

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

Solution 3

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!

Solution 4

Python 3 has a different and simpler syntax for calling parent method.

If Foo class inherits from Bar, then from Bar.__init__ can be invoked from Foo via super().__init__():

class Foo(Bar):

    def __init__(self, *args, **kwargs):
        # invoke Bar.__init__
        super().__init__(*args, **kwargs)

Solution 5

Many answers have explained how to call a method from the parent which has been overridden in the child.

However

"how do you call a parent class's method from child class?"

could also just mean:

"how do you call inherited methods?"

You can call methods inherited from a parent class just as if they were methods of the child class, as long as they haven't been overwritten.

e.g. in python 3:

class A():
  def bar(self, string):
    print("Hi, I'm bar, inherited from A"+string)

class B(A):
  def baz(self):
    self.bar(" - called by baz in B")

B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"

yes, this may be fairly obvious, but I feel that without pointing this out people may leave this thread with the impression you have to jump through ridiculous hoops just to access inherited methods in python. Especially as this question rates highly in searches for "how to access a parent class's method in Python", and the OP is written from the perspective of someone new to python.

I found: https://docs.python.org/3/tutorial/classes.html#inheritance to be useful in understanding how you access inherited methods.

Share:
769,552
jjohn
Author by

jjohn

I am a veteran web/cloud developer (Perl/Ruby/Python/Java) in the Boston area. I contributed to the O'Reilly titles Programming Web Application with XML-RPC and Unix Power Tools, 3rd. ed. I was a regular contributor to The Perl Journal. See https://www.taskboy.com/ for contact/resume details, but I am not on the market.

Updated on July 15, 2022

Comments

  • jjohn
    jjohn almost 2 years

    When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this:

    package Foo;
    
    sub frotz {
        return "Bamf";
    }
    
    package Bar;
    @ISA = qw(Foo);
    
    sub frotz {
       my $str = SUPER::frotz();
       return uc($str);
    }
    

    In Python, it appears that I have to name the parent class explicitly from the child. In the example above, I'd have to do something like Foo::frotz().

    This doesn't seem right since this behavior makes it hard to make deep hierarchies. If children need to know what class defined an inherited method, then all sorts of information pain is created.

    Is this an actual limitation in python, a gap in my understanding or both?