python类 返回属性值_python __del__调用,返回类属性和对象属性的差别

麻烦各位大神帮我看一下这三段代码的输出之间的差别第一段代码:classInstCt(object):count=0#countisclassattrcount是一个类属性def__init__(self):#incrementcount增加countInstCt....

麻烦各位大神帮我看一下这三段代码的输出之间的差别

第一段代码:

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呢?

展开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值