I am working with some code that has 3 levels of class inheritance. From the lowest level derived class, what is the syntax for calling a method 2 levels up the hierarchy, e.g. a super.super call? The "middle" class does not implement the method I need to call.
Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'.
In Java, a class cannot directly access the grandparent's members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor's member in the inheritance hierarchy. In Java, we can access grandparent's members only through the parent class.
super() Python: Inherit from __init__() To do so, we can make use of the super() function. super() allows you to access methods of a parent class inside a child class. In our example, our parent class is called CheckingAccount, and our child class is called ChildAccount.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
Well, this is one way of doing it:
class Grandparent(object): def my_method(self): print "Grandparent" class Parent(Grandparent): def my_method(self): print "Parent" class Child(Parent): def my_method(self): print "Hello Grandparent" Grandparent.my_method(self)
Maybe not what you want, but it's the best python has unless I'm mistaken. What you're asking sounds anti-pythonic and you'd have to explain why you're doing it for us to give you the happy python way of doing things.
Another example, maybe what you want (from your comments):
class Grandparent(object): def my_method(self): print "Grandparent" class Parent(Grandparent): def some_other_method(self): print "Parent" class Child(Parent): def my_method(self): print "Hello Grandparent" super(Child, self).my_method()
As you can see, Parent
doesn't implement my_method
but Child
can still use super to get at the method that Parent
"sees", i.e. Grandparent
's my_method
.
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