属性包装器方法是Python中一个不错的特性,但这个问题并不是关于此特性的。我想知道是否可以在Python析构函数__del__
中使用它,一个实际的例子可能是数据库连接。为简化起见,假设我们有以下类:
class Point(object):
"""docstring for Point"""
def __init__(self, x, y):
self.x = x
self.y = y
@property
def x(self):
print('x getter got called')
return self._x
@x.setter
def x(self, x):
print('x setter got called')
self._x = x
def __str__(self):
return '[%s:%s]' % (self.x, self.y)
def __del__(self):
print('destructor got called')
del self.x
del self.y
作为一个测试案例,我们假设有以下内容:
a = Point(4, 5)
del a
输出结果为:
Exception AttributeError: "can't delete attribute" in <bound method Point.__del__ of <__main__.Point object at 0x7f8bcc7e5e10>> ignored
如果我们删除属性部分,一切都会顺利进行。有人可以指出问题在哪里吗?
del self._x
。 - salparadise__del__
来处理这个问题,因为这很容易导致内存泄漏。相反,你应该使用上下文管理器。 - juanpa.arrivillaga