【问题标题】:calling super class init when child class is created using type()使用 type() 创建子类时调用超类 init
【发布时间】:2017-11-11 00:21:44
【问题描述】:

我正在尝试使用 python type() 方法动态创建一个类。

所以,假设我有一个基类“A”

>>> class A:
    def __init__(self):
        print("I am in init of A..")

现在我使用类型方法创建一个子类“C”

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

当我创建一个对象时

>>> c = C()
I am in init of A..

基类的init也调用正确..

现在我想在我的 init 方法中做点什么,我写了一个自定义的 init 方法..

>>> def BsInit(self):
    print ("I am in init of B..")

我创建了一个“B”类并创建了一个实例..

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
I am in init of B..

根本不调用A类的init..

所以尝试像这样修改 BsInit 方法:

>>> def BsInit(self):
    super().__init__();
    print ("I am in init of B..")

创建实例时出现以下错误...

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    b = B()
  File "<pyshell#19>", line 2, in BsInit
    super().__init__();print ("I am in init of B..")
RuntimeError: super(): __class__ cell not found

我找到的所有使用 type() 的自定义 init 示例都非常简单,就像初始化一个变量一样。但是如果我也想调用基类 Init 怎么办??

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您需要在 init 方法中传递 cls 而不是 self。以下是您的问题的解决方案:

    def init(cls):
        super(type(cls), cls).__init__()
    
    B = type('B',(A,),{'__init__':init})
    b = B()
    "I am in init of A.."
    

    【讨论】:

    • 我认为 cls 和 self 在这种情况下都是相同的。. cls 和 self 之间的区别只是一种编码约定:stackoverflow.com/questions/4613000/… 所以下面的也适用:def BsInit(self): super (type(self),self).__init__(); print ("我在初始化 B..")
    【解决方案2】:

    你需要这样称呼它:super(B, self).__init__()

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 2016-01-28
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      相关资源
      最近更新 更多