Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 615
jjohn Avatar asked Apr 30 '09 01:04

jjohn


People also ask

Can I access a parent class method by a child class object?

The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.

How do you call a method of parent class by an object of a child class in Java?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method. This would print: I'm the child.

How do you access parent members in the child class Python?

Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

Can a parent class inherit from a child class Python?

Classes called child classes or subclasses inherit methods and variables from parent classes or base classes. We can think of a parent class called Parent that has class variables for last_name , height , and eye_color that the child class Child will inherit from the Parent .


1 Answers

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) 
like image 88
Adam Rosenfield Avatar answered Oct 02 '22 17:10

Adam Rosenfield