python入门第三天——类

# # -*-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实例


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值