我运行的程序是
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
知道为什么第二次输出会改变吗?
请您参考如下方法:
啊,现在知道了!..大问题!..
在第二次运行中:
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
