2015-06-05 32 views
0

我有一個擁有大量參數的超類。我想創建一個共享所有這些參數並添加額外的一個或兩個參數的子類。到ommit雙編碼,我以前在Avoid specifying all arguments in a subclass規定的方法:Python:未指定子類__init__中的變量,調用方法存在問題

class Container(Item): 

    def __init__(self,**kwargs): 
    try: self.is_locked=kwargs.pop('is_locked') 
    except KeyError: pass 
    super(Container, self).__init__(**kwargs) 

    def open(self): 
    print "aw ys" 

然而,當我然後嘗試調用容器類的對象:

> some_container.open() 
AttributeError: 'Item' object has no attribute 'open' 

它看起來好像some_container是不是一個Container(),而是添加了一個變量is_locked的Item()。我究竟做錯了什麼?

編輯:我的項目定義:

class Item(object: 
def __init__(self,istemplate,id,short,long,type,flags,value,damagerange,damagereductionrange,weight): 
    if istemplate==False: 
     self.__class__.instances.append(self) 
    self.istemplate=istemplate 
(... many variables like that...) 
    self.id=id 
    self.randomizestuff() 
    if istemplate==True: 
     self.__class__.templates.append(copy.deepcopy(self)) 
+0

你的'Item'類定義是什麼? –

+0

哎呀,對不起。編輯成主帖。 – user2551153

+0

我想'some_container'就像'some_container =集裝箱(...)' – Pynchia

回答

0

好了,一些研究也證明後,我實際上引用不some_container.open(容器),而是通過一個函數創建一個動態的項目創建來自同一模板的項目實例。該函數將新實例定義爲Item(...)而不是Container(...),因爲它是在引入任何子類之前創建的。

some_container=Container(...) 
some_container.open() 

以上將工作從一開始,因此paidhima無法複製我的錯誤。

相關問題