Python 多重继承,给予双亲';构造函数是一个参数
在python 2.7中,我有以下情况:Python 多重继承,给予双亲';构造函数是一个参数,python,python-2.7,multiple-inheritance,Python,Python 2.7,Multiple Inheritance,在python 2.7中,我有以下情况: class A(object): def __init__(self, a): self._a = a class B(object): def __init__(self, b): self._b = b class C(A, B): def __init__(self): # How to init A with 'foo' and B with 'b
class A(object):
def __init__(self, a):
self._a = a
class B(object):
def __init__(self, b):
self._b = b
class C(A, B):
def __init__(self):
# How to init A with 'foo' and B with 'bar'?
还应该注意的是,父类之一,比如A,是一个库类,解决方案最好假设它是固定的;而另一个B级是我的,可以自由更换
正确初始化两个父类的正确方法是什么?
谢谢 颠倒继承顺序,让您的类调用库1上的
super
:
In [1375]: class A(object):
...: def __init__(self, a):
...: self._a = a
...:
...: class B(object):
...: def __init__(self, b, a):
...: self._b = b
...: super().__init__(a)
...:
...: class C(B, A):
...: def __init__(self):
...: super().__init__('bar', 'foo')
...:
In [1376]: c = C()
In [1377]: c._a
Out[1377]: 'foo'
In [1378]: c._b
Out[1378]: 'bar'
基本思想是修改您的超类以接受两个参数,一个为自身,另一个将传递给MRO
另外,您可以在Python3中从对象
中删除继承
编辑: Python 2需要使用参数进行
super
调用:
class B(object):
def __init__(self, b, a):
self._b = b
super(B, self).__init__(a)
class C(B, A):
def __init__(self):
super(C, self).__init__('bar', 'foo')
谢谢不过我问的是python 2.7@nodwj检查我的编辑。