麻烦各位大神帮我看一下这三段代码的输出之间的差别
第一段代码:
class InstCt(object):
count = 0 # count is class attr count 是一个类属性
def __init__(self): # increment count 增加 count
InstCt.count += 1
def __del__(self): # decrement count 减少 count
InstCt.count -= 1
def howMany(self): # return count 返回 count
return InstCt.count
a = InstCt()
b = InstCt()
print b.howMany()
print a.howMany()
del b
print a.howMany()
del a
print InstCt.count
第二段代码:
class InstCt(object):
count = 0 # count is class attr count 是一个类属性
def __init__(self): # increment count 增加 count
self.count += 1
def __del__(self): # decrement count 减少 count
self.count -= 1
def howMany(self): # return count 返回 count
return self.count
a = InstCt()
c=a
b = InstCt()
print b.howMany()
print a.howMany()
del b
print a.howMany()
del a
print InstCt.count
第三段代码:
class InstCt(object):
count = 0 #
def __init__(self):
InstCt.count += 1
def __del__(self):
InstCt.count -= 1
def howMany(self):
return InstCt.count
a = InstCt()
c=a
b = InstCt()
print a.howMany()
print c.howMany()
print b.howMany()
del b
print a.howMany()
del a
print InstCt.count
主要我不明白以下情况:
1> 第一段代码和第二段代码就只是改了InstCt.count和self.count,为什么会使得结果不同?
2> 第三段代码中,c=a应该是增加了一次引用计数(删除a和b,再print InstCt.count,此时输出为1,也证明了这一点),那为什么前面a.howMany()、b.howMany()、c.howMany()都是2而不是3呢?