Python类的定义与使用

 1 #! /usr/bin/python
 2 # Filename:objvar.py
 3 
 4 class Person:
 5     '''Represents a person.'''
 6     population = 0
 7 
 8     def __init__(self, name):
 9         ''' Initializes the person's data. '''
10         self.name = name
11         print '(Initializeing %s)' % self.name
12 
13         # When this person is created, he/she adds to the population
14         Person.population += 1
15     
16     def __del__(self):
17         ''' I am dying. '''
18         print '%s says bye.' % self.name
19 
20         self.__class__.population -= 1
21 
22         if self.__class__.population == 0:
23             print 'I am the last one.'
24         else:
25             print 'There are still %d people left.' % Person.population
26     
27     def sayHi(self):
28         ''' Greeting by the person.
29         Really, that's all it does. '''
30         print 'Hi, my name is %s.' % self.name
31 
32     def howMany(self):
33         ''' Prints the current population. '''
34         if Person.population == 1:
35             print 'I am the only person here.'
36         else:
37             print 'We have %d persons here.' % Person.population
38 
39 # The definion of class is end
40 
41 zjw = Person('zjw')
42 zjw.sayHi()
43 zjw.howMany()
44 
45 lbz = Person('lbz')
46 lbz.sayHi()
47 lbz.howMany()
48 
49 zjw.sayHi()
50 zjw.howMany()
View Code

 

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

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

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

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

posted @ 2013-09-25 02:10  冷冰若水  阅读(1236)  评论(0编辑  收藏  举报