首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python类的_init_方法和_del_方法,该如何解决

2012-05-20 
python类的__init__方法和__del__方法Python codeclass Person():population0def __init__(self,name):se

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__.我当初也和你一样,就因为这个执行时间不确定,折磨了我一个晚上.

热点排行