【问题标题】:Python class instance vs. class variablesPython 类实例与类变量
【发布时间】:2015-07-10 02:26:57
【问题描述】:

我试图将列表定义为类中的实例变量,但它充当类变量。

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}

当我想要(并期望)增加一个实例变量时,我似乎在为 July1,2015 增加一个类字典元素。

帮助

【问题讨论】:

  • 您重用了datecnts 来构造THING 的两个实例,并且当您创建一个新列表时,两者之间的dict 内部是相同的。
  • 也许你可以打印 type(item) 以确保对象是 THING 而不是 dict
  • Python 没有办法将其打印出来,因此如果您只想打印出变量,则必须创建 def __str__(self)

标签: python


【解决方案1】:

当您将datecnts 列表传递给您的THING 对象的构造函数时,您只是传递了引用(并且列表是可变的并且字典是可变的),因此如果您对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)))

【讨论】:

  • 请记得采纳答案,如果对您有帮助,对社区也有帮助。
  • 点击左侧的勾号即可接受答案。
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 2013-03-24
  • 2014-09-21
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多