class Member(object):
def __init__(self, identifier):
self.identifier = identifier
print "Member __init__", self.identifier
def __del__(self):
print "Member __del__", self.identifier
with open("/home/might/" + self.identifier, "w") as outF:
outF.write(self.identifier)
class WithMembers(object):
def __init__(self):
print "WithMembers __init__"
print WithMembers.classMem
self.instanceMem = Member("instance mem")
def __del__(self):
print "WithMembers __del__"
classMem = Member("class mem")
if __name__ == "__main__":
print "main"
WithMembers()
#del WithMembers.classMem # "Member __del__ class mem" before "end"
#del WithMembers # "Member __del__ class mem" after "end"
print "end"
上述代码在 Hidden.py 文件中,运行
python Hidden.py
将产生以下输出结果:Member __init__ class mem
main
WithMembers __init__
<__main__.Member object at 0x935aeec>
Member __init__ instance mem
WithMembers __del__
Member __del__ instance mem
end
除非我取消其中一个del
语句,否则我不会在输出或class mem
文件中看到Member __del__ class mem
。为什么会这样?Python类和类属性何时进行垃圾回收?
del <identifier>
会取消引用该标识符,因此它不再指向现有对象。当发生这种情况时,将调用your_object.__del__
。稍后,在没有对该对象的任何引用后,它将被垃圾回收。 - Adam Smith