如何从孙子类调用超级方法? [英] How to call super method from grandchild class?

查看:28
本文介绍了如何从孙子类调用超级方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些具有 3 级类继承的代码.从最低级别的派生类开始,调用方法 2 的语法是什么?一个 super.super 电话?中间"类没有实现我需要调用的方法.

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.

推荐答案

好吧,这是一种方法:

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)

也许不是你想要的,但除非我弄错了,否则它是最好的 python.您所问的问题听起来很反 Python,您必须解释为什么要这样做,以便我们为您提供快乐的 Python 做事方式.

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()

如你所见,Parent 没有实现 my_methodChild 仍然可以使用 super 来获取 的方法Parent看到",即Grandparentmy_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.

这篇关于如何从孙子类调用超级方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆