Using __del__ with property methods in place

Property wrapping methods is a good function that python has, this question is not the subject of such a question, I need to know whether it can be used with a python destructor __del__, a practical example could be a database to simplify, say, we have the following class:

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

as a test example, let's say:

a = Point(4, 5)
del a

Conclusion:

Exception AttributeError: "can't delete attribute" in <bound method Point.__del__ of <__main__.Point object at 0x7f8bcc7e5e10>> ignored

if we removed part of the property, everything goes smoothly. can anyone show where the problem is?

+4
source share
2 answers

Add a deleter xthat performs the cleanup to your resource . By default, if a property is defined fdel, is displayed AttributeError, you see :

@x.deleter
def x(self):
    print("x deleter got called")
    del self._x
+3

@x.deleter (, @x.setter), .

+2

Source: https://habr.com/ru/post/1686353/


All Articles