#! /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函数中不能访问全局变量,因此就修改成了现在这个这样,使用对象的一个方法间接的访问到了全局变量。

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

最新文章

  1. \r与\n的区别
  2. 从零开始使用Jenkins来构建Docker容器(Ubuntu 14.04)
  3. 【随笔】使用mOnOwall封禁某一个ip
  4. [小北De编程手记] : Lesson 08 - Selenium For C# 之 PageFactory &amp; 团队构建
  5. LINUX下安装TeamViewer
  6. HDU 3065 (AC自动机模板题)
  7. Servlet连接数据库
  8. Java基本类型
  9. using System.Reflection;
  10. XML字符串转化json
  11. 备胎的养成记KeepAlived实现热备负载
  12. Struts(五)之OGNL、contextMap
  13. DBA Scripts
  14. serversql数据库的查询操作
  15. react-native中的props
  16. TASE2017
  17. cSharp:use Activator.CreateInstance with an Interface?
  18. Ubuntu下禁止自动打开U盘等设备
  19. logstash 使用kafka范例
  20. BF字符串匹配算法

热门文章

  1. SQL语句执行时间测试
  2. Leetcode: Remove Elements
  3. csuoj 1115: 最短的名字
  4. Centos配置Caffe详解
  5. Python快速建站系列-Part.One-组装开发环境
  6. C# 控制台程序如何防止启动多个实例
  7. 有趣的linux命令
  8. [Ubuntu] google chrome乱码
  9. React快速入门
  10. Bonbo Git Server