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([])

跪求好的解法! 謝謝

Python: default value to a constructor parameter 有 “ 1 則迴響 ”

發表留言