- 论坛徽章:
- 0
|
今天学习看了简明Python教程关于类的介绍,有一个Person的类的例子,我把它简化了一下,代码如下:- class Person:
- population = 0
- def __init__(self, name):
- self.name = name
- print("Initialising a person:%s" %self.name)
- Person.population += 1
- def __del__(self):
- print("%s is dead." %self.name)
- Person.population -= 1
- Tom = Person("Tom")
- Jim = Person("Jim")
-
复制代码 在windows的cmd中执行的时候,如果执行的次数多了以后就会出现如下的错误:
Initialising a person:Tom
Initialising a person:Jim
Jim is dead.
Exception AttributeError: "'NoneType' object has no attribute 'population'" in <
bound method Person.__del__ of <__main__.Person object at 0x00C2B9F0>> ignored
Tom is dead.
Exception AttributeError: "'NoneType' object has no attribute 'population'" in <
bound method Person.__del__ of <__main__.Person object at 0x00B5DAD0>> ignored
在网上找了很多,解决方法也比较简单,把Person.population 换成 self.__class__.population 即可,出现的原因是因为垃圾回收机制,
我想问一下,是什么样的垃圾回收机制导致这种情况的出现??
为什么使用self.__class__.population就可以解决,他和Person.population有什么区别呢??
|
|