【问题标题】:python dynamic multiple inheritance __init__python动态多重继承__init__
【发布时间】:2018-04-20 17:06:36
【问题描述】:

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

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'

这是因为当 C 类的实例初始化时,只有 A 类的 init 正在运行。我的问题是如何让 C 类在初始化 C 类的实例时同时运行 A 类的 init 和 B 类的 init .我确实意识到,如果我有像下面这样的 C 类,它会起作用:

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

但是,鉴于我需要继承的类的动态列表,这将不起作用。

【问题讨论】:

  • 使用super(),它正是针对这种情况而设计的。

标签: python class multiple-inheritance


【解决方案1】:

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

要使多重继承起作用,祖父类__init__ 签名与该方法的所有兄弟的签名相匹配是很重要的。为此,请定义一个公共父类(在此示例中为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)

您可以根据需要为MyParent 定义任意数量的子级,然后将调用所有__init__ 方法,前提是您正确使用了super()

【讨论】:

  • 感谢您的回答。你能告诉我为什么 MyParent 的 init 中有一个 super 吗?
  • 它调用object.__init__... 它什么都不做,但你不应该依赖它什么都不做。它是父类的初始化,所以你应该总是调用它
猜你喜欢
  • 2012-01-31
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多