![](/img/trans.png)
[英]How to change an instance variable of a class when that variable is inside a list
[英]Instance variable of type list behaves as class variable
在以下代碼中,我認為list
對於每個構造的對象來說都是唯一的變量。 為什么將其作為類變量共享?
01 class Thing(object):
02 def __init__(self, my_list=[]):
03 self.list = my_list
04 return
05
06 thing1=Thing()
07 thing2=Thing()
08 thing1.list.append(1)
09 print thing2.list
id(thing1)
與id(things2)
不同,但id(thing1.list)
與id(thing2.list)
相同。
如果在第3行上使用self.list = []
,則每個Thing
的屬性都是唯一的。 如果在第6行上使用thing1 = Thing(my_list=[])
,並且在第7行上使用類似的屬性,則每個Thing
的屬性都是唯一的。
我在Canopy環境中運行Python 2.7。
您應該這樣做:
01 class Thing(object):
02 def __init__(self, my_list=None):
03 if my_list is None:
04 my_list = []
04 self.list = my_list
有關關鍵字參數為何如此行為的說明,請參見這篇文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.