Python类的定义与使用

 #! /usr/bin/python
# Filename:objvar.py class Person:
'''Represents a person.'''
population = 0 def __init__(self, name):
''' Initializes the person's data. '''
self.name = name
print '(Initializeing %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 if self.__class__.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population def sayHi(self):
''' Greeting by the person.
Really, that's all it does. '''
print 'Hi, my name is %s.' % self.name def howMany(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 # The definion of class is end zjw = Person('zjw')
zjw.sayHi()
zjw.howMany() lbz = Person('lbz')
lbz.sayHi()
lbz.howMany() zjw.sayHi()
zjw.howMany()

  程序刚开始是有错误的,就是在__del__函数中如果使用Person.population来调用全局变量的话,会出现下面这个错误

Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0xb72e9aec>> ignored

在网上搜了一下,应该是说在del函数中不能访问全局变量,因此就修改成了现在这个这样,使用对象的一个方法间接的访问到了全局变量。

发现现在网上到处都是转载的文章,很少用真正原创的,我想说的是,就算是转载的,也请你看懂了之后再转,否则还是半知半解,只是在网络上图增垃圾而已。这个问题我还没搞明白到底的原因,如果哪位知道是什么原因,请留言告诉我,谢谢。

上一篇:HTML5拖放API


下一篇:PDF 补丁丁 0.5 正式版发布