【发布时间】: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