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?
Your
__del__
method assumes that the class is still present by the time it is called.This assumption is incorrect.
Groupclass
has already been cleared when your Python program exits and is now set toNone
.Test if the global reference to the class still exists first:
or use
type()
to get the local reference:but do note that this means that the semantics for
count
change ifGroupclass
is subclassed (each subclass gets a.count
attribute versus onlyGroupclass
having a.count
attribute).Quoting from the
__del__
hook documentation:If you are using Python 3, two additional notes apply:
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 no longer sets globals to
None
(in most cases), as per Safe Object Finalization; see PEP 442.