我跑的程序是
class Account(object):
counter = 0
def __init__(self, holder, number, balance, credit_line = 1500):
Account.counter += 1
def __del__(self):
Account.counter -= 1
print "Counter\t", Account.counter
a1 = Account("Homer Simpson", 2893002, 2325.21)
print "Counter\t", Account.counter
a2 = Account("Fred Flintstone", 2894117, 755.32)
print "Counter\t", Account.counter
a3 = a2
print "Counter\t", Account.counter
a4 = Account("Bill Gates", 2895007, 5324.32)
print "Counter\t", Account.counter
del a4
print "Counter\t", Account.counter
我第一次运行它时输出是正确的:
Counter 0
Counter 1
Counter 2
Counter 2
Counter 3
Counter 2
但如果我在同一个控制台中再次运行它:
Counter 0
Counter 0
Counter 1
Counter 0
Counter 1
Counter 0
知道输出第二次改变的原因吗?
答案 0 :(得分:-1)
啊,现在知道了!很好的问题!..
在第二轮中:
print "Counter\t", Account.counter #Class instantiated. Prints 0
a1 = Account("Homer Simpson", 2893002, 2325.21) #a1 is dereferenced and referenced again!..
上面发生的是创建一个新的Account对象。因此递增计数器。但是当a1再次引用它时,它所引用的同一个前一个对象就会丢失!因此调用 del 并收集垃圾,减少数量为1。
print "Counter\t", Account.counter #Thus no change as referencing dereferencing happen together.Prints 0.
a2 = Account("Fred Flintstone", 2894117, 755.32)
现在等一下,它接下来打印1。那个怎么样?上面发生了什么?现在记住a2和a3都引用同一个对象。当a2引用新对象时,旧对象不会被垃圾收集,因为a3仍然引用它并因此引用该增量。
print "Counter\t", Account.counter #Gets incremented and prints 1 as explained above.
a3 = a2
现在你可能会得到它;-) ..没有创建新对象但是之前引用的对象的最后一个引用丢失了,因为a3引用了一个新对象,从而减少了计数。
print "Counter\t", Account.counter #Count decremented print 0 as explained above.
a4 = Account("Bill Gates", 2895007, 5324.32)
这里有点棘手,但等等。请记住,您已在上次运行中删除了a4。因此创建了一个全新的对象,增加了计数。
print "Counter\t", Account.counter #count incremented prints 1
del a4
现在你必须得到它。好问题!.. :-D
print "Counter\t", Account.counter
抱歉可怕的编辑。这里相当新,手头上没有多少时间,但无法回答:-P