Sea*_*abs 40 python inheritance super grandchild python-2.7
我正在使用一些具有3级继承级别的代码.从最低级派生类,调用方法2的语法是什么,层次结构升级,例如super.super调用?"中间"类没有实现我需要调用的方法.
Cra*_*sta 62
嗯,这是一种方法:
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)
Run Code Online (Sandbox Code Playgroud)
也许不是你想要的,但它是最好的蟒蛇,除非我弄错了.你问的是什么声音反pythonic,你必须解释为什么你这样做让我们给你快乐的python做事方式.
另一个例子,也许你想要的(来自你的评论):
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()
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,Parent
没有实现my_method
,但Child
仍然可以使用超级获得在该方法Parent
"看到",即Grandparent
的my_method
.
小智 33
这对我有用:
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"
super(Parent, self).my_method()
Run Code Online (Sandbox Code Playgroud)
如果你想提升两个级别,为什么不直接做
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
Run Code Online (Sandbox Code Playgroud)
您可以添加一些防御性的内容,例如检查是否__bases__
为空,或者如果您的中类具有多重继承,则对其进行循环。嵌套 super 不起作用,因为 super 的类型不是父类型。
归档时间: |
|
查看次数: |
61863 次 |
最近记录: |