__del__ 上的 Python 属性错误 [英] Python attributeError on __del__
问题描述
我有一个 python 类对象,我想分配一个类变量的值
I have a python class object and I want to assign the value of one class variable
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()
这个执行结果是正确的,但是有一条错误信息说:
This execution result is correct, but there's an error message that says:
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method Groupclass.__del__ of <__main__.Groupclass instance at 0x00BA6710>> ignored
谁能告诉我我做错了什么?
Can someone tell me what me I did wrong?
推荐答案
您的 __del__
方法假定该类在调用时仍然存在.
Your __del__
method assumes that the class is still present by the time it is called.
这个假设是错误的.Groupclass
在 Python 程序退出时已被清除,现在设置为 None
.
This assumption is incorrect. Groupclass
has already been cleared when your Python program exits and is now set to None
.
先测试类的全局引用是否仍然存在:
Test if the global reference to the class still exists first:
def __del__(self):
if Groupclass:
Groupclass.count -= 1
或者使用type()
获取本地引用:
or use type()
to get the local reference:
def __del__(self):
type(self).count -= 1
但请注意,这意味着如果 Groupclass
是子类化的,count
的语义会发生变化(每个子类都获得一个 .count
属性,而不是只有Groupclass
具有 .count
属性).
but do note that this means that the semantics for count
change if Groupclass
is subclassed (each subclass gets a .count
attribute versus only Groupclass
having a .count
attribute).
引用 __del__
钩子文档:
警告:由于__del__()
方法被调用的不稳定情况,在执行过程中发生的异常会被忽略,并且会向sys.stderr
代替.此外,当 __del__()
被调用以响应一个模块被删除时(例如,当程序执行完成时),__del__()
方法引用的其他全局变量可能已经被删除或正在被拆除(例如进口机器关闭).出于这个原因,__del__()
方法应该做到维护外部不变量所需的绝对最低限度.从版本 1.5 开始,Python 保证名称以下划线开头的全局变量在删除其他全局变量之前从其模块中删除;如果不存在对此类全局变量的其他引用,这可能有助于确保在调用 __del__()
方法时导入的模块仍然可用.
Warning: Due to the precarious circumstances under which
__del__()
methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed tosys.stderr
instead. Also, when__del__()
is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the__del__()
method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason,__del__()
methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the__del__()
method is called.
如果您使用的是 Python 3,请注意以下两点:
If you are using Python 3, two additional notes apply:
CPython 3.3 自动应用随机散列盐 到
globals
字典中使用的str
键;这也会影响清理全局变量的顺序,并且可能是您只在某些运行中看到问题.
CPython 3.3 automatically applies a randomized hash salt to the
str
keys used in aglobals
dictionary; this also affects the order in which globals are cleaned up, and it could be that you see the problem on only some of the runs.
CPython 3.4 不再根据 安全对象终结;请参阅 PEP 442.
CPython 3.4 no longer sets globals to None
(in most cases), as per Safe Object Finalization; see PEP 442.
这篇关于__del__ 上的 Python 属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!