Python 3.x 使用super的动态类继承
我正在尝试使用Python 3.x 使用super的动态类继承,python-3.x,object,inheritance,superclass,Python 3.x,Object,Inheritance,Superclass,我正在尝试使用type()动态创建一个类,并分配一个调用super()的构造函数;但是,当调用super()时,我收到以下错误: TypeError: super(type, obj): obj must be an instance or subtype of type 这是我的密码: class Item(): def __init__(self, name, description, cost, **kwargs): self.name
type()
动态创建一个类,并分配一个调用super()的构造函数;但是,当调用super()
时,我收到以下错误:
TypeError: super(type, obj): obj must be an instance or subtype of type
这是我的密码:
class Item():
def __init__(self, name, description, cost, **kwargs):
self.name = name
self.description = description
self.cost = cost
self.kwargs = kwargs
class ItemBase(Item):
def __init__(self, name, description, cost):
super().__init__(name, description, cost)
def __constructor__(self, n, d, c):
super().__init__(name=n, description=d, cost=c)
item = type('Item1', (ItemBase,), {'__init__':__constructor__})
item_instance = item('MyName', 'MyDescription', 'MyCost')
为什么super()
在\uuuuu构造函数\uuuu
方法中不理解对象参数;我该如何解决这个问题呢?以下是我解决这个问题的方法。我引用type()
def __constructor__(self, n, d, c, h):
# initialize super of class type
super(self.__class__, self).__init__(name=n, description=d, cost=c, hp=h)
# create the object class dynamically, utilizing __constructor__ for __init__ method
item = type(item_name, (eval("{}.{}".format(name,row[1].value)),), {'__init__':__constructor__})
# add new object to the global _objects object to be used throughout the world
self._objects[ item_name ] = item(row[0].value, row[2].value, row[3].value, row[4].value)
也许有更好的方法来实现这一点,但我需要一个修复,这就是我想到的。。。如果可以,请使用它。注意,如果动态创建的类作为self继承,sadmove的解决方案将创建一个无限循环。\uuuuu class\uuuu
将对应于子类
不存在此问题的另一种方法是在创建类后分配\uuuu init\uuuu
,例如,可以通过闭包显式链接该类。例如:
#基类
类别A():
定义初始化(自):
打印('A')
#动态创建的类
B=类型('B',(A,),{})
定义初始化(自):
打印('B')
super(B,self)。\uuuuu init\uuuuuuu()
B.。uuu init_uuuu=uuuu init__
#儿童班
丙(乙)类:
定义初始化(自):
打印('C')
super()。\uuuu init\uuuuu()
C()#打印C、B、A