Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call super method from grandchild class?

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.

like image 346
SeanLabs Avatar asked Jul 05 '15 15:07

SeanLabs


People also ask

How do you call super super class in Python?

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'.

How do you call a grandparent class in Java?

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.

How do you use child class super in Python?

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.

What is super () method in Python?

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.


1 Answers

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.

like image 156
CrazyCasta Avatar answered Sep 22 '22 10:09

CrazyCasta