python请简述构造函数和析构函数的作用_python – 构造函数和析构函数如何工作?...

我正在尝试理解这段代码:

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”程序/类中添加一些东西?

输出:

Initializing person data

******************************************

Initializing Rohan

******************************************

Population now is: 1

Hi My name is Rohan

i am the only one here

Initializing person data

******************************************

Initializing Sanjivi

******************************************

Population now is: 2

In case Person dies:

******************************************

Sanjivi Bye Bye world

there are still 1 people left

i am the only one here

In case Person dies:

******************************************

Rohan Bye Bye world

i am the last person on earth

Population now is: 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值