How to 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?

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)

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

Python is a language with multiple inheritance, which means that a class can have several direct superclasses. But for the purposes of calling super(), Python always linearizes the inheritance hierarchy to determine who the "best" superclass is. This is called the method resolution order, accessed via the __mro__ variable in Python.

So if we have the class hierarchy

class A(object): pass
class B(A): pass
class C(A): pass
class D(B, C): pass

Then although D has two superclassses, if we say super() in D, it'll only give us B. That's because the MRO for D creates a linear hierarchy for us. In Python 3, it uses an algorithm called the C3 resolution, which gives us this hierarchy

>>> D.__mro__
(<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>)

So if we call super() in a method on class D, we'll get the version on B, and if we call super() from there, we'll get the C version, then the A version, and finally the object one.

So in your case, C inherits from A and B (in that order), so it's going to be biased toward A. That is, the MRO for the class C in your example is (C, A, B, object). If you want it to always go for B and then A, then simply switch the order of the superclasses.

class C(B, A):
...

This is the best solution. It's predictable and Python programmers will immediately understand the intention of a super() call in this class. I recommend this if it fits your needs.

However, if you have a complicated multi-inheritance system and need access to both the A and B superclasses at the same time, you can always call them directly with a class name, forgoing the super() call altogether.

class C(B, A):
def some_method(self):
A.some_method(self) # Calls A's version on self
B.some_method(self) # Calls B's version on self

If some_method takes some arguments, you can pass them after the explicit self argument. This is going to raise more eyebrows, so if you find yourself needing access to two distinct superclass methods in complicated ways, you might consider refactoring your code to use less multiple inheritance. But the feature is there if you really need it.

Calling a child method in a parent class in Python

Python is rather programmer confident at this level. You can always call a cry method from a class even if it is not defined in the class. Python will just trust you to provide an object that knows of the cry method at the time if will be called.

So this is perfectly fine:

class Parent:
def makeChildrenStopCry(self):
if self.cry():
self.doWhateverToStopCry()

class Children(Parent):
crying = False
def makeCry(self):
self.crying = True
def doWhateverToStopCry(self):
self.crying = False
def cry(self):
return self.crying

It gives in an interactive session:

>>> child = Children()
>>> child.makeCry()
>>> print(child.crying)
True
>>> child.makeChildrenStopCry()
>>> print(child.crying)
False

Calling a parent method from a child class with a variable of that child

The answer to the question turned out to be more complex than I expected. Example of it you can check in my GitHub repo

How to call a overwritten parent-method from within a parent-class?

You would have to hard-code a reference to Parent, as you don't want to delegate attribute lookup to the object itself. You can use the special name __class__ to avoid duplicating the name Parent in the code.

class Parent:
def calculate(self, n):
return n + 10

def print_plus_ten(self, n):
print(__class__.calculate(self, n))

How to require child class method to call parent class method?

Non-Virtual Interface idiom has the base class define a public
non-virtual member function, and a private virtual member function that
is an override point for derived classes.

The public non-virtual member function acts as a public facing API.

The private virtual member function acts as a class hierarchy
facing API.

Separating those two concerns can be a handy technique especially
for larger projects, and for debugging purposes, and for ensuring
pre- and post- operations in the base class's public non-virtual
member function.

#include <iostream>

using std::cout;

namespace {

class A {
virtual void MyMethodImpl() const {
// Derived classes should override this virtual member function
// and add their extra steps there.
}
public:
virtual ~A() = default;
A() {}

void MyMethod() const {
cout << "A::MyMethod before steps.\n";
MyMethodImpl();
cout << "A::MyMethod after steps.\n";
}
};

class B : public A {
void MyMethodImpl() const override {
cout << "B::MyMethodImpl extra steps.\n";
}
public:
B() {}
};

} // anon

int main() {
B b;
b.MyMethod();
}

how to call parent class methods in python?

Use super(ClassName, self)

class my_class(object):
def __init__(self):
# build my objects
def foo(self,*args,**kwargs):
# do something with them

class my_extended_class(my_class):
def foo(self,*args,**kwargs):
super(my_extended_class, self).foo(*args,**kwargs)
# other child-specific statements
return self

Compatibility is discussed in How can I call super() so it's compatible in 2 and 3? but in a nutshell, Python 3 supports calling super with or without args while Python 2 requires them.



Related Topics



Leave a reply



Submit