2010-10-27 37 views
0

請原諒糟糕的標題 - 我很難想出一個簡潔的方式來解釋這一點。Python - 如何使用底層對象的構造函數作爲類方法?

我有一個Python類,將有一些其他類的基礎對象。我希望能夠通過原始對象的方法創建這些底層對象。讓我試着解釋用一個例子更好:

class Foo: 
    def __init__(self): 
     self.bars = [] 

    def Bar(self, a, b, c): 
     self.bars.append(Bar(a, b, c)) 

class Bar: 
    def __init__(self, a, b, c): 
     self.a = a 
     self.b = b 
     self.c = c 

我會用上面這樣:

f = Foo() 
f.Bar(1, 2, 3) 

所以這個作品我怎麼想,但就是那種蹩腳關於維護。有沒有一種很好的「Pythonic」方式來做到這一點,這將使維持這一點變得簡單?舉例來說,假設我改變了Bar的構造器:

__init__(self, a, b, c, d): 

會有一個方法來定義這一切,所以我不必更新3個地方的參數列表?

回答

3

當然,沒問題:只要通過*args and **kwargsBar

class Foo: 
    def __init__(self): 
     self.bars = [] 

    def append_bar(self, *args, **kwargs): 
     self.bars.append(Bar(*args, **kwargs)) 

class Bar: 
    def __init__(self, a, b, c, d): 
     self.a = a 
     self.b = b 
     self.c = c 
     self.d = d 

f=Foo() 
f.append_bar(1,2,3,4) 

PS。我將該方法的名稱更改爲append_bar,因爲Python中的usual convention將爲方法使用小寫名稱,我認爲名稱爲動詞的方法有助於描述該方法的用途。

+0

這很好用!謝謝! – brady 2010-10-27 22:48:27

相關問題