+ -
当前位置:首页 → 问答吧 → python 类的析构问题

python 类的析构问题

时间:2011-10-17

来源:互联网

在练习python的时候遇到一个问题,请教大家。
先贴代码:
class Person:
  population = 0

  def __init__(self, name):
  self.name = name
  print "Add name", self.name
  Person.population += 1

  def __del__(self):
  print "Remove name", self.name
  Person.population -= 1
  if Person.population == 0:
  print "I'm the only one."
  else:
  print "There are", Person.population, "person left."


  def sayHi(self):
  print "Hello, my name is", self.name
  if Person.population == 1:
  print "I'm the last one."
  else:
  print "There are", Person.population, "person left."

  def howMany(self):
  if Person.population == 1:
  print "There is only one person here."
  else:
  print "There is %d person here" % Person.population

  b = Person("brian")
  b.sayHi()
  b.howMany()

  t = Person("Tom")
  t.sayHi()
  t.howMany()

  b.sayHi()
  b.howMany()


打印的结果为:

Add name brian
Hello, my name is brian
I'm the last one.
There is only one person here.
Add name Tom
Hello, my name is Tom
There are 2 person left.
There is 2 person here
Hello, my name is brian
There are 2 person left.
There is 2 person here
Remove name brian
There are 1 person left.
Remove name Tom
Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__
main__.Person instance at 0xb738380c>> ignored

我觉得可能是:
Person类已经被从内存中清除,所以也就找不到该类对应的变量population。


请求大牛解答,谢谢。

作者: zhyajshhz   发布时间: 2011-10-17

Python code
这样贴代码

作者: thundor   发布时间: 2011-10-17