多重继承并将参数传递给python中的继承类

时间:2019-05-08 05:55:58

标签: python python-2.7 class inheritance multiple-inheritance

我定义了以下类:

class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.c = ""

    def mA1(self):
        print "Method 1 in A"

    def mA2(self):
        print "Method 2 in A"

    def mA3(self):
        print "Method 3 in A"

class B(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.x = 0

    def mB1(self):
        print "Method 1 in B"

class C(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.c = ""
        self.y = 1

    def mC1(self):
        print "Method 1 in C"

    def mC2(self):
        print "Method 2 in C"

可以看出,它们在构造函数中采用相同的输入参数。现在,我想创建一个类D,该类继承自ABC的全部,以便可以将参数直接传递给D'的构造函数如下:

clsT = D(1, 2)

因此,如here所述,我尝试了以下修订的定义:

class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.c = ""

    def mA1(self):
        print "Method 1 in A"

    def mA2(self):
        print "Method 2 in A"

    def mA3(self):
        print "Method 3 in A"


class B(A):
    def __init__(self, **kw):
        super(B, self).__init__(**kw)
        self.x = 0

    def mB1(self):
        print "Method 1 in B"


class C(A):
    def __init__(self, **kw):
        super(C, self).__init__(**kw)
        self.c = ""
        self.y = 1

    def mC1(self):
        print "Method 1 in C"

    def mC2(self):
        print "Method 2 in C"


class D(A, B, C):
    def __init__(self, a, b):
        super(D, self).__init__(a=a, b=b)


ci = D(1, 2)

print "a = ", ci.a
print "b = ", ci.b
print "c = ", ci.c
print "x = ", ci.x
print "y = ", ci.y

以上内容似乎无效,并给我以下错误:

    class D(A, B, C):
TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution
order (MRO) for bases B, C, A

可能出了什么问题?确实需要BC必须包含super()并在中级基类上创建线性继承吗?除了我的解释,还有其他选择吗?如果没有,我该如何调整才能使它正常工作?

1 个答案:

答案 0 :(得分:2)

我如下更改了D的类定义,并且它起作用了

class D(B, C, A):
    def __init__(self, a, b):
        super(D, self).__init__(a=a, b=b)

所以整个类看起来像(我删除了使代码简短的方法)

class A(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.c = ""

class B(A):
    def __init__(self, **kw):
        super(B, self).__init__(**kw)
        self.x = 0

class C(A):
    def __init__(self, **kw):
        super(C, self).__init__(**kw)
        self.c = ""
        self.y = 1


class D(B, C, A):
    def __init__(self, a, b):
        super(D, self).__init__(a=a, b=b)


c = D(1, 2)
print(c.a, c.b, c.x, c.c, c.y)

输出将为

1 2 0  1

这是由于MRO算法中的一条规则所致(此处的更多详细信息,answer,但要旨是

  

一个类总是出现在其祖先之前(“单调性”)

因此B和C必须出现在A之前,因为A是B和C的祖先

或者换句话说: D从A,B和C继承。由于B和C已经从A继承,因此python现在无法确定首先要查找哪种类的方法。如果使用旧的定义顺序,则为A或B和C。 D(A, B, C)