How to call super method from grandchild class?

前端 未结 5 635
无人共我
无人共我 2020-12-05 16:57

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,

5条回答
  •  猫巷女王i
    2020-12-05 17:49

    You can do this by following ways

    class Grandparent(object):
        def my_method(self):
            print "Grandparent"
    
    class Parent(Grandparent):
        def my_other_method(self):
            print "Parent"
    
    class Child(Parent):
        def my_method(self):
            print "Inside Child"
            super(Child, self).my_method()
    

    In this case Child will call base class my_method but base class my_method is not present there so it will call base class of parent class my_method in this way we can call my_method function of grandparent

    Another Way

    class Grandparent(object):
        def my_method(self):
            print "Grandparent"
    
    class Parent(Grandparent):
        def my_other_method(self):
            print "Parent"
    
    class Child(Parent):
        def my_method(self):
            print "Inside Child"
            super(Parent, self).my_method()
    

    In this way we are directly calling function base class my_method function of the parent class

    Another way but not pythonic way

    class Grandparent(object):
        def my_method(self):
            print "Grandparent"
    
    class Parent(Grandparent):
        def my_other_method(self):
            print "Parent"
    
    class Child(Parent):
        def my_method(self):
            print "Inside Child"
            Grandparent.my_method()
    

    In this way we are directly calling my_method function by specifying the class name.

提交回复
热议问题