#!/usr/bin/env python #!-*- coding=utf-8 -*- #Filename:objvar.py classPerson: '''Represents a person''' population = 0 def__init__(self,name): '''Initializes the person's data. ''' self.name = name print'(Initializes %s)' % self.name #When this person is created, he/she #adds to the population Person.population += 1 def__del__(self): ''' I am dying. ''' print'%s says bye.' % (self.name) self.__class__.population -= 1 ifself.__class__.population != 0: print'There are still %d people left.' % self.__class__.population else: print'I am last one' defsayHi(self): ''' Greeting by the person, Really, That's all it does ''' print'Hi ,my name is %s.' % self.name defhowMany(self): ''' prints the current population. ''' if Person.population == 1: print'I am the only person here.' else: print'We have %d persons here.' % Person.population durban = Person('Durban') durban.sayHi() durban.howMany() david = Person('David') david.sayHi() david.howMany() durban.sayHi() durban.howMany()
gowhich得到的结果如下:
1 2 3 4 5 6 7 8 9 10 11 12
(Initializes Durban) Hi ,my name is Durban. I am the only person here. (Initializes David) Hi ,my name is David. We have 2 persons here. Hi ,my name is Durban. We have 2 persons here. Durban says bye. There are still 1 people left. David says bye. I am last one