How to call super method from grandchild class?

前端 未结 5 626
无人共我
无人共我 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条回答
  •  爱一瞬间的悲伤
    2020-12-05 17:38

    If you want two levels up, why not just do

    class GrandParent(object):                                                       
    
        def act(self):                                                               
            print 'grandpa act'                                                      
    
    class Parent(GrandParent):                                                       
    
        def act(self):                                                               
            print 'parent act'                                                       
    
    class Child(Parent):                                                             
    
        def act(self):                                                               
            super(Child.__bases__[0], self).act()                                    
            print 'child act'                                                        
    
    
    instance = Child()                                                               
    instance.act()
    
    # Prints out
    # >>> grandpa act
    # >>> child act      
    

    You can add something defensive like checking if __bases__ is empty or looping over it if your middle classes have multiple inheritance. Nesting super doesn't work because the type of super isn't the parent type.

提交回复
热议问题