2014-05-11 53 views
0

我的問題是關於爲什麼默認參數不能用來區分不同的對象。爲什麼默認參數不適用於Python對象區分

如果我定義類M1爲:

class M1: 
    id = -1 
    list1 = [] 
    def __init__(self,id,list1 = []): 
     self.id = id 
     self.list1 = list1 
    def insertList(self,element): 
     self.list1.append(element) 

而且使用它像:

if __name__ == '__main__': 
    m1 = M1(1,[]) 
    m1.insertList("a",[]) 
    m1.insertList("b",[]) 
    m2 = M1(2,[]) 
    print m2.list1 

因爲list1的是不是M1和M2之間共享它會返回[]作爲m2.list1。

但是,如果我「信任」默認參數時我定義M1對象,象下面這樣:

if __name__ == '__main__': 
    m1 = M1(1) 
    m1.insertList("a",[]) 
    m1.insertList("b",[]) 
    m2 = M1(2) 
    print m2.list1 

它將返回[「一」,「B」]爲m2.list1和list1的之間共享不同的對象。

我知道類參數可以定義爲靜態或對象成員的基礎上它是否定義在__init__(self),但爲什麼默認參數會影響結果?

回答

3

這是關於列表是可變的,一流的對象(見"Least Astonishment" and the Mutable Default Argument)。它會工作,如果你這樣做:

def __init__(self, id, list1=None): 
    if list1 is None: 
     self.list1 = [] 

函數體內的一個賦值將刷新變量。

+0

我最近讀了一篇很棒的博文(http://www.toptal.com/python/top-10-mistakes-that-python-programmers-make),這篇文章以我特別清楚的方式討論過這個問題,也許這對你也是有用的。 – TML

+0

@TML謝謝!我仍然試圖自己弄清楚一流的物體。 –

+0

謝謝@亞歷山大,對我來說很好! – linpingta

相關問題