cll*_*ach 0 python inheritance super method-resolution-order
我有一个继承的类并覆盖了一个也从基类继承的方法.但问题是中间方法创建了一个异常,我想通过调用第一个声明的方法来绕过它.有没有办法指定忽略第二次调用的mro?
一个例子可能是:
class Base(object):
def __init__(self):
res = "Want this"
print res
class BaseA(Base):
def __init__(self):
res = super(BaseA, self).__init__()
res = "Not this"
print res
class BaseB(BaseA):
def __init__(self):
res = super(BaseB, self).__init()
#At this poing res is "Not this"
#The desire is that it would be "Want this"
print res
Run Code Online (Sandbox Code Playgroud)
非常感谢
PD:像BaseB(Base,BaseA)这样的东西可以工作吗?
通常你会修复那个方法.
但是,第一个参数super()是开始搜索下一个方法的地方.通常,这是当前的类,但您也可以传入基类:
class BaseB(BaseA):
def __init__(self):
res = super(BaseA, self).__init__()
Run Code Online (Sandbox Code Playgroud)
在这里,super()获取MRO ,在MRO中type(self)找到BaseA,并寻找下一个类实现__init__.
绕过有问题的__init__方法的另一种方法是直接调用未绑定的方法Base:
class BaseB(BaseA):
def __init__(self):
res = Base.__init__(self)
Run Code Online (Sandbox Code Playgroud)
彻底绕过任何MRO搜索.
| 归档时间: |
|
| 查看次数: |
588 次 |
| 最近记录: |