【发布时间】:2015-12-08 06:07:16
【问题描述】:
我正在查看 Stack Overflow 问题 Counting instances of a class?,我不确定为什么该解决方案有效,而使用简单加法的解决方案无效。我想这更多是关于如何存储和访问类与实例变量的问题。
这是我认为应该可以工作的代码,但会为每个 id 生成 4:
class foo():
num = 3 # trying 3 instead of 0 or 1 to make sure the add is working
def __init__(self):
self.num += 1
self.id = self.num
f = foo()
g = foo()
print f.id # 4
print g.id # 4
self.num +=1 语句有些工作(正在添加,但没有赋值)。
到底发生了什么导致此分配在这里失败,而 itertools.count 分配在另一个问题的解决方案中成功?
【问题讨论】:
标签: python python-2.7 python-internals