如何调用超级方法? [英] How to call super method?

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

问题描述

我正在使用一些具有3级级别继承的代码。从最底层的派生类,调用方法2的层次结构的语法是什么?一个super.super调用? 中间类没有实现我需要调用的方法。

解决方案

嗯,这是一种做法:

  class祖父母(对象):
def my_method(self):
打印祖父母

class父(祖父母):
def my_method(self):
printParent

class Child(Parent):
def my_method (自):
打印你好祖父母
祖父母(个人)

也许不是你想要的,但它是最好的python有,除非我错了。你所要求的听起来像是反pythonic,你必须解释你为什么要这样做,让我们给你快乐的python做事方式。



另一个例子,也许你想要的(从你的评论):

 类祖父母(对象):
def my_method自我):
打印祖父母

class父母(祖父母):
def some_other_method(self):
打印父

class Child(Parent):
def my_method(self):
printHello Grandparent
super(Child,self).my_method()

如您所见,不实现 my_method Child 仍然可以使用super来获取 Parent 看到的方法,即祖父母 my_method


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.

解决方案

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.

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

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