2010年9月7日 星期二

Python: default value to a constructor parameter

我們有一個 class X
constructor 有一個參數 x
我們想給 x 預設值為一個空的 set
直覺會這樣子寫:

class X(object):
def __init__(self, x=set([])):
self.x = x


只是會發生不符合預期的結果:

a = X()
b = X()
print a.x is b.x # True <-- not expected! a.x 和 b.x 指到了同一個 set([])

a.x.add(1)
print a.x # set([1])
print b.x # set([1]) <-- not expected!


目前是這樣子來避開這個問題

class X(object):
def __init__(self, x=None)):
self.x = x
if x is not None else set([])


跪求好的解法! 謝謝

1 則留言:

  1. 這沒解, 見 http://code.google.com/p/soc/wiki/PythonStyleGuide#Default_Argument_Values 和 http://www.deadlybloodyserious.com/2008/05/default-argument-blunders/

    回覆刪除