我有一个python类对象,我想分配一个类变量的值
class Groupclass(Workerclass):
"""worker class"""
count = 0
def __init__(self):
"""initialize time"""
Groupclass.count += 1
self.membercount = 0;
self.members = []
def __del__(self):
"""delte a worker data"""
Groupclass.count -= 1
if __name__ == "__main__":
group1 = Groupclass()
此执行结果正确,但有一条错误消息显示:
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method Groupclass.__del__ of <__main__.Groupclass instance at 0x00BA6710>> ignored
有人能告诉我我做错了什么吗?
您的
__del__
方法假设类在被调用时仍然存在。这种假设是错误的。
Groupclass
在Python程序退出时已被清除,现在设置为None
。测试对类的全局引用是否仍然存在:
或者使用
type()
获取本地引用:但请注意,这意味着如果
Groupclass
是子类,那么count
的语义就会改变(每个子类都有一个.count
属性,而只有Groupclass
有一个.count
属性)。引用
__del__
钩子文档:如果您使用的是Python3,则需要另外两个注意事项:
CPython 3.3会自动将randomized hash salt应用到
str
字典中使用的globals
键;这也会影响全局数据的清理顺序,而且可能会只在运行的部分上看到问题。CPython 3.4不再根据Safe Object Finalization将全局变量设置为
None
(在大多数情况下);请参见PEP 442。相关问题 更多 >
编程相关推荐