如何从孙子类中调用超级方法? [英] How to call super method from grandchild class?
问题描述
我正在处理一些具有3级继承级别的代码。从最低级别的派生类,调用方法2的语法是什么?超级电话? 中间类没有实现我需要调用的方法。
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,除非我弄错了。你问的是什么声音反pythonic,你必须解释为什么你这样做让我们给你愉快的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_method
但是 Child
仍然可以使用super来获取 Parent
看到的方法,即祖父母
的 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屋!