#!/usr/bin/python# Filename: objvar.pyclassPerson:'''Represents a person.'''
population =0def__init__(self, name):'''Initializes the person's data.'''
self.name = name
print'(Initializing %s)'% self.name
# When this person is created, he/she# adds to the population
Person.population +=1def__del__(self):'''I am dying.'''print'%s says bye.'% self.name
Person.population -=1if Person.population ==0:print'I am the last one.'else:print'There are still %d people left.'% Person.population
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
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
析构函数的执行有问题,按照他这个思路输入后,对象在创建之后直接析构
# -*- coding: utf-8 -*-"""
Created on Wed May 15 20:39:20 2019
@author: 激光雷达
"""classPerson(object):
population =0def__init__(self,name):
self.name = name
print('(Initialing%s)'%self.name)
self.__class__.population +=1defsayHi(self):print('Hi , My name is', self.name)defhowMany(self):if self.__class__.population ==1:print('I am the only one here')else:print('We are %d people here .'%self.__class__.population)def__del__(self):
self.__class__.population -=1if self.__class__.population ==0:print('%s Say Byebye'%self.name)print('I am the last one.')else:print('%s Say Byebye'%self.name)print('There are still %d person.'%self.__class__.population)
liweibing = Person('liweibing')
liweibing.sayHi()
liweibing.howMany()
chenxin = Person('chenxin')
chenxin.sayHi()
chenxin.howMany()
liweibing.sayHi()
liweibing.howMany()del liweibing
del chenxin