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。
请求大牛解答,谢谢。
先贴代码:
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
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28