看到python简明教程的objvar.py这节,有关于__init__(初始函数),__del__(类似于析构函数)。代码如下:
#Filename : objvar.py
class Person :
'''Represents a person.'''
population = 0
def __init__(self,name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)'%self.name
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.'%self.name
Person.population -= 1
if Person.population == 0 :
print 'I am the lastone.'
else :
print 'There are still %d people left.'%Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.'%self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here'
else:
print 'We have %d persons here.'%Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('AbdulKalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
看教材上的运行结果应该是:
但是呢,我运行的结果是:
不一样啊,那就查找下,如:
http://babocs.ycool.com/post.2664695.html
http://topic.csdn.net/t/20060625/19/4842245.html
看了这两个地方,那么就在后面加了两句,
del swaroop
del kalam
再次运行,如下图:
原来是要用del去激活它。