python 动态多重继承 __init__

python dynamic multiple inheritance __init__

我正在尝试编写一个插件环境,我需要在其中对未知数量的 classes 进行多重继承。因此,我选择使用类型 class creation:

class A(object):
   def __init__(self,s):
      self.a="a"
   def testA(self,x):
      print(x)

class B(object):
   def __init__(self,s):
      self.b="b"
   def testA(self,x):
      print(x)

C = type('C', (A,B), {})

x= C("test")
print x.b

当我运行上面的代码时,我得到错误:

AttributeError: 'C' object has no attribute 'b'

这是因为 class C 的实例初始化时,只有 class A 的 init 正在 运行。我的问题是如何让 class C 同时拥有 class A 的 init 以及 init for class B to 运行 when an instance of class C is initialized.我确实意识到,如果我有像下面这样的 class C,它就会起作用:

class C(A,B):
    def __init__(self,s):
       A.__init__(self,s)
       B.__init__(self,s)

但是,考虑到我需要继承 classes 的动态列表,这是行不通的。

您似乎在使用 python 2 所以我使用的是旧的 python 2 super() 语法,您必须在其中指定 class 和实例,尽管它也适用于 python 3。在 python 3 中,您还可以使用不带参数的较短的 super() 形式。

为了使多重继承起作用,重要的是 grandparent class __init__ 签名与该方法的所有兄弟姐妹的签名相匹配。为此,定义一个公共 parent class(本例中为 MyParent),其 __init__ 具有与所有子项相同的参数列表。它将负责为我们调用 object__init__,它不带任何参数。

from __future__ import print_function

class MyParent(object):
    def __init__(self, s):
        super(MyParent, self).__init__()

class A(MyParent):
    def __init__(self, s):
        self.a = "a"
        super(A, self).__init__(s)
    def testA(self, x):
        print(x)

class B(MyParent):
    def __init__(self, s):
        self.b = "b"
        super(B, self).__init__(s)

    def testA(self,x):
        print(x)

C = type('C', (A, B), {})

x = C("test")
print(x.b)

您可以根据需要定义任意多个 children 到 MyParent,然后将调用所有 __init__ 方法,前提是您正确使用了 super()