python入门第三天——类

来源:互联网 发布:上古卷轴5清理脏数据 编辑:程序博客网 时间:2024/06/08 01:33
# # -*-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.personnumberkalam = Person("Kalam")kalam.sayHi()kalam.howMany()print '\n'swaroop = Person("Swaroop")swaroop.sayHi()swaroop.howMany()print 'over\n'对应运行结果:Initializing KalamHi my name is Kalami am the only person hereInitializing SwaroopHi my name is Swaroopthere are 2 person over##del执行的一步Kalam say bye.There are still 1 people leftdestory the KalamSwaroop say bye.I am the last onedestory the Swaroop###del执行,对象被销毁,在程序的所有代码运行完之后再销毁对象###init方法用一个名字来初始化person实例

原创粉丝点击