HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfromparentclassmethodchildcallpython

Problem

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?

Solution

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


For Python class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)

Context

Stack Overflow Q#805066, score: 1066

Revisions (0)

No revisions yet.