首页 文章

使用super的动态类继承

提问于
浏览
2

我正在尝试使用 type() 动态创建一个类,并分配一个 __init__ 构造函数,该函数调用 super().__init__(...) ;但是,当 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() 方法中的 super() 不理解对象参数;我该如何解决?

1 回答

  • 2

    这是我如何解决这个问题 . 我引用 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)
    

    可能有更好的方法来实现这一目标,但我需要一个解决方案,这就是我想出来的......如果可以,请使用它 .

相关问题