python中是否可以从层次结构中的特定类调用方法?
#!/usr/bin/python3
class Base:
def f1( self ):
print("f1 from Base")
class Derived ( Base ):
def f1( self ):
print("f1 from Derived")
class Derived2 ( Derived ):
def f1( self ):
print("f2 from Derived2")
super( ).f1()
d2 = Derived2()
d2.f1()
使用super
来电是下一个更高的电话。我是否也可以编写它,以便派生类方法f1
将从Base调用f1
答案 0 :(得分:0)
如果你知道这个类叫什么(在这种情况下是Base
)你可以直接调用它的方法:
class Derived2(Derived):
def f1(self):
print("f2 from Derived2")
Base.f1(self)
如果你需要更深入地了解方法解析顺序,你可能会混淆Derived2.__mro__
(这会调用object
的第一个孩子):
class Derived2(Derived):
def f1(self):
print("f2 from Derived2")
Derived2.__mro__[-2].f1(self)