2012-11-21 136 views
1

我試圖在Python中創建對象列表。下面的代碼應該(希望)解釋我在做什麼:循環並創建對象數組

class Base(object): 
    @classmethod 
    def CallMe(self): 
     out = [] 
     #another (models) object is initialised here which is iterable 
     for model in models: 
      #create new instance of the called class and fill class property 
      newobj = self.__class__() 
      newobj.model = model 
      out.append(newobj) 
     return out 


class Derived(Base): 
    pass 

我想初始化類,如下所示:

objs = Derived.CallMe() 

我想「OBJ文件」包含的對象列表我可以迭代。

我得到的堆棧跟蹤以下錯誤:TypeError: type() takes 1 or 3 arguments在包含newobj = self.__class__()

是否有某種方式來做到這一點,或者線路我在看問題的錯誤的方式?

+0

您的問題和示例並未顯示需要使用類和類方法。有沒有一個,或者你可以使用一個函數作爲工廠來構建你的對象列表?簡單通常更好。 – Petri

回答

7

問題是classmethod未收到實例(self)作爲參數。相反,它接收到它所調用的類對象的引用。通常這個參數被命名爲cls,儘管這個約定不如self那麼強大(並且偶爾會看到帶有名字的代碼,例如klass)。

因此,不要致電self.__class__()來創建您的實例,只需致電cls()即可。如果函數被調用爲Derived.CallMe()Base實例(如果調用爲Base.CallMe()),則會獲得Derived實例。

@classmethod 
def CallMe(cls):  # signature changed 
    out = [] 
    models = something() 
    for model in models: 
     newobj = cls() # create instances of cls 
     newobj.model = model 
     out.append(newobj) 
    return out 
+0

這麼簡單,但只是我沒有嘗試過的唯一!謝謝。 –

1

既然你做了它類方法,其self參數不是一個實例,但類本身。所以你想要做self()。出於這個原因,習慣上命名類方法的第一個參數不是self,而是cls