如何调用超级方法? [英] How to call super method?
问题描述
嗯,这是一种做法:
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屋!