我正在尝试理解这段代码:
class Person:
'''Represents a person '''
population = 0
def __init__(self,name):
//some statements and population += 1
def __del__(self):
//some statements and population -= 1
def sayHi(self):
'''grettings from person'''
print 'Hi My name is %s' % self.name
def howMany(self):
'''Prints the current population'''
if Person.population == 1:
print 'i am the only one here'
else:
print 'There are still %d guyz left ' % Person.population
rohan = Person('Rohan')
rohan.sayHi()
rohan.howMany()
sanju = Person('Sanjivi')
sanju.howMany()
del rohan # am i doing this correctly?
析构函数是自动调用的,无需在“main”程序/类中添加任何内容吗?
输出:
初始化人员数据 ****************************************** 初始化Rohan ****************************************** 现在人口是:1 嗨,我的名字是Rohan 我在这里是唯一的一个人 初始化人员数据 ****************************************** 初始化Sanjivi ****************************************** 现在人口是:2 如果Person死了: ****************************************** Sanjivi再见世界 还有1个人留下来 我在这里是唯一的一个人 如果Person死了: ****************************************** Rohan再见世界 我是地球上最后一个人 现在人口是:0
__del__
的自然反应,而不是问题本身。"解释__del__
"会让有经验的程序员哭泣。 - Charles Merriam