python类的__init__方法和__del__方法

belukwill 2012-04-25 10:39:24
class Person():
population=0
def __init__(self,name):
self.name=name
#print 'my name\' is %s' % self.name
Person.population+=1
def sayHi(self):
print 'hello everyone,my name\' is %s'% self.name
def howMany(self):
if Person.population==1:
print "I am the only one here"
else:
print "we have %d people here" % Person.population
def __del__(self):
print '%s say bye,' % self.name
Person.population-=1
if Person.population==0:
print 'I am the last one here'
else:
print 'we still have %d people here' % Person.population
john=Person('john')
john.sayHi()
john.howMany()

smith=Person('smith')
smith.sayHi()
smith.howMany()

打印结果:
hello everyone,my name' is john
I am the only one here
hello everyone,my name' is smith
we have 2 people here
smith say bye,
we still have 1 people here
john say bye,
...全文
673 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
JennyHui 2014-05-20
  • 打赏
  • 举报
回复
为什么我的运行结果是这个:
Mavarick 2013-07-24
  • 打赏
  • 举报
回复
测试一下,发现如果只删一个的话,del john和del smith的输出是不一样的,如果删掉del john,则正常;如果删除del smith,则结果报错:Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0x2adfcb7dd8c0>> ignored 这个执行时间不确定,应该有一定的规律!具体什么情况,等待大神解答!
cliffbaby 2012-05-13
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 的回复:]

刚注册完就让我看到了,哈哈
_del__()的调用是在对象销亡时执行(即彻底不再使用时),但执行时间不能确定.所以,你可以在原来代码最后加上两行,del john和del smith来删除对象,使其立即调用__del__.我当初也和你一样,就因为这个执行时间不确定,折磨了我一个晚上.
[/Quote]

原来如此,学习了!
pythondao 2012-05-10
  • 打赏
  • 举报
回复
最近也开始看看Python
insomn 2012-04-26
  • 打赏
  • 举报
回复
刚注册完就让我看到了,哈哈
_del__()的调用是在对象销亡时执行(即彻底不再使用时),但执行时间不能确定.所以,你可以在原来代码最后加上两行,del john和del smith来删除对象,使其立即调用__del__.我当初也和你一样,就因为这个执行时间不确定,折磨了我一个晚上.
belukwill 2012-04-26
  • 打赏
  • 举报
回复
我也是2.7.2的![Quote=引用 5 楼 的回复:]
楼主什么版本?我是2.7.2,没啥问题好像

Python code
*** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. ***
>>>
hello everyone,my name' is john
I am the only one here
hello ……
[/Quote]
belukwill 2012-04-25
  • 打赏
  • 举报
回复
不好意思没注意,贴上来怎么就没缩进了。。[Quote=引用 1 楼 的回复:]
丢了缩进,python代码就没法看!!!
[/Quote]
薛定谔之死猫 2012-04-25
  • 打赏
  • 举报
回复
丢了缩进,python代码就没法看!!!
libralibra 2012-04-25
  • 打赏
  • 举报
回复
楼主什么版本?我是2.7.2,没啥问题好像
*** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. ***
>>>
hello everyone,my name' is john
I am the only one here
hello everyone,my name' is smith
we have 2 people here
>>> john say bye,
we still have 1 people here
smith say bye,
I am the last one here

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧