Suppose I have two classes (one a parent and one a subclass). How do I refer to a method in the parent class if the method is also defined in the subclass different?
Here is the code:
class A: def __init__(self, num): self.value=num def f(self, num): return self.value+2 class B(A): def f(self, num): return 7*self.f(num)
In the very last line, I want to refer to the parent class A with the "self.f(num)" command, not the method itself in B which would create an infinite recursion. Thank you in advance.
When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
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.
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.
If you know you want to use A you can also explicitly refer to A in this way:
class B(A): def f(self,num): return 7 * A.f(self,num)
remember you have to explicitly give the self argument to the member function A.f()
Use super
:
return 7 * super(B, self).f(num)
Or in python 3, it's just:
return 7 * super().f(num)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With