有没有办法让类删除自己的实例。我知道对于变量,你可以做del x
,但对于类,你如何做到这一点?如果我做了这样的事情:
class foo(object):
x=5
def __init__(self):
print "hi"
def __del__(self):
del self
print "bye"
a = foo()
a.__del__()
print a.x
代码的输出是
hi
bye
5
foo的实例未被删除。有没有办法让一个班这样做?
否,如果您有对该类实例的引用,那么根据定义,它还有剩余的引用。可以使用del
关键字删除名称(释放对对象的引用),但如果对实例的引用保留在其他位置,则实例将保留。
如果您想要的是确定性清理行为,请不要使用__del__
(它以明显或一致的方式不具有确定性,并且在Python 3.4之前,如果循环的任何成员是定义__del__
终结器的类的实例,则可能导致引用循环泄漏)。让类实现上下文管理器协议,并使用带有with
语句的实例来获得确定性清理;在最后一个引用消失之前,实例仍然存在,但只要__exit__
执行必要的资源释放,实例的空壳几乎不会花费任何成本。
作为上下文管理的一个例子,我们将使x
成为foo
的实例属性,而不是类属性,并且我们需要确保实例对x
的引用在已知的时间消失(注意,由于del
只是删除了我们的引用,如果其他人保存了a.x
,则在其他引用也被释放之前,对象实际上不会被释放):
class foo(object):
def __init__(self, x):
self.x = x
print "hi"
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print "bye"
del self.x
with foo(123456789) as a:
print a.x # This works, because a.x still exists
# bye is printed at this point
print a.x # This fails, because we deleted the x attribute in __exit__ and the with is done
# a still exists until it goes out of scope, but it's logically "dead" and empty
通过定义__del__
,我相信您正在覆盖del
的默认行为。正如您在这里所读到的,一旦对象的引用计数达到0,就会调用__del__
。除非您知道自己在做什么,否则不建议使用__del__
。
编辑:这是不正确的,请检查shadowranger的答案。尽管链接仍然与python 2 相关
del a
应该做到这一点:
代码:
class foo(object):
x=5
def __init__(self):
print "hi"
def __del__(self):
del self
print "bye"
a = foo()
del a
print a.x
输出:
$ python test.py
hi
here
bye
Traceback (most recent call last):
File "test.py", line 12, in <module>
print a.x
NameError: name 'a' is not defined