__del__上的Python attributeError

__del__上的Python attributeError,第1张

概述我有一个 python类对象,我想分配一个类变量的值 class Groupclass(Workerclass): """worker class""" count = 0 def __init__(self): """initialize time""" Groupclass.count += 1 self.memberc 我有一个 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 -= 1if __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__方法假定该类在调用时仍然存在.

这个假设是不正确的.当您的Python程序退出时,Groupclass已被清除,现在设置为None.

测试全局对类的引用是否仍然存在:

def __del__(self):    if Groupclass:        Groupclass.count -= 1

或者使用type()获取本地引用:

def __del__(self):    type(self).count -= 1

但请注意,这意味着如果Groupclass被子类化(每个子类获取.count属性,而仅具有.count属性的Groupclass),则计数更改的语义将更改.

引用__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 to sys.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,则需要另外两个注意事项:

> cpython 3.3自动将randomized hash salt应用于全局词典中使用的str键;这也会影响全局变量的清除顺序,也可能只在一些运行中看到问题.
>根据Safe Object Finalization,cpython 3.4不再将全局变量设置为None(大多数情况下)见PEP 442.

总结

以上是内存溢出为你收集整理的__del__上的Python attributeError全部内容,希望文章能够帮你解决__del__上的Python attributeError所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1206975.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存