python类的__init__方法和__del__方法
- Python code
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.populationjohn=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,
[解决办法]
刚注册完就让我看到了,哈哈
_del__()的调用是在对象销亡时执行(即彻底不再使用时),但执行时间不能确定.所以,你可以在原来代码最后加上两行,del john和del smith来删除对象,使其立即调用__del__.我当初也和你一样,就因为这个执行时间不确定,折磨了我一个晚上.