我正在尝试将列表定义为类中的实例变量,但它充当类变量。
class THING:
def __init__(self, name, stuff):
self.name = name
self.dict = []
for item in stuff:
self.dict.append(item)
def getname(self):
return self.name
def getlist(self):
return self.dict
def inc_datecnt(self,date):
for item in self.dict:
if item.has_key(date):
item[date] += 1
list = []
dates=['July1,2015', 'July2,2015', 'July3,2015']
datecnts = []
for date in dates:
datecnts.append({date : 0})
list.append(THING('A', datecnts))
list.append(THING('B', datecnts))
for item in list:
print "\n", item.getname()
item.inc_datecnt('July1,2015')
for subitem in item.getlist():
print subitem
当我执行此操作时,我得到:
A
{'July1,2015': 1}
{'July2,2015': 0}
{'July3,2015': 0}
B
{'July1,2015': 2}
{'July2,2015': 0}
{'July3,2015': 0}
当我希望(并且期望)增加一个实例变量时,我似乎在为2015年7月1日增加一个单独的字典元素。
帮助
答案 0 :(得分:1)
当您将datecnts
列表传递给THING
对象的构造函数时,您只是传递引用(并且列表是可变的并且dict是可变的),因此如果您进行任何更改对于A
THING对象的字典,它会反映在B
中,因为B
也具有相同的引用。您应该尝试copy.deepcopy
datecnts
A
并将其分别发送给B
和import copy
list.append(THING('A', copy.deepcopy(datecnts)))
list.append(THING('B', copy.deepcopy(datecnts)))
。
示例 -
downloader/lib/Mage/HTTP/Client/Curl.php