2015-12-07 32 views
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()__constructor__方法不理解對象參數;我該如何解決它?

回答

1

下面是我如何解決這個問題。我引用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) 

可能有更好的方法來做到這一點,但我需要修復,這就是我想出了...使用如果可以的話。