# # -*-coding:utf-8-*-
class Person:
personnumber = 0
def __init__(self,name):
self.name=name
print 'Initializing %s'%self.name
Person.personnumber +=1
def __del__(self):##在程序结束时,自动销毁对象
print '%s say bye.'%self.name
Person.personnumber -=1
if Person.personnumber==0:
print 'I am the last one'
print 'destory the %s' % self.name
else:
print 'There are still %d people left'%Person.personnumber
print 'destory the %s' % self.name
def sayHi(self):
print 'Hi my name is %s' % self.name
def howMany(self):
if Person.personnumber==1:
print 'i am the only person here'
else:
print 'there are %d person '%Person.personnumber
kalam = Person("Kalam")
kalam.sayHi()
kalam.howMany()
print '\n'
swaroop = Person("Swaroop")
swaroop.sayHi()
swaroop.howMany()
print 'over\n'
对应运行结果:
Initializing Kalam
Hi my name is Kalam
i am the only person here
Initializing Swaroop
Hi my name is Swaroop
there are 2 person
over
##del执行的一步
Kalam say bye.
There are still 1 people left
destory the Kalam
Swaroop say bye.
I am the last one
destory the Swaroop
###del执行,对象被销毁,在程序的所有代码运行完之后再销毁对象
###init方法用一个名字来初始化person实例
python入门第三天——类
最新推荐文章于 2022-11-30 19:29:58 发布