Reputation:
I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google.
What I would like to achieve is when this deleter behavior is called, I can trigger other actions (e.g: using my 3d application SDK).
For now just a simple print() doesn't seem to get triggered.
Is deleter fired when I delete the property using del(instance.property) ?
Otherwise, how can I achieve this?
class M():
def __init__(self):
self._m = None
@property
def mmm(self):
return self._m
@mmm.setter
def mmm(self, val):
self._m = val
@mmm.deleter
def mmm(self):
print('deleting') # Not printing
del(self._m)
if __name__ == '__main__':
i = M()
i.mmm = 150
print(i.mmm)
del(i.mmm)
print(i.mmm)
Thank you very much (:
Upvotes: 19
Views: 16176
Reputation: 882351
In Python 3 you WOULD see the print
's result -- and then an AttributeError for the last print (because _m
has disappeared). You may be using Python 2.6, in which case you need to change the class
clause to class M(object):
to make M
new-style, and then you'll get the same behavior as in Python 3.
Upvotes: 9
Reputation: 880509
Make M a new-style class:
class M(object):
See http://www.python.org/download/releases/2.2.3/descrintro/#property:
Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its dict without calling the property's set method, and after that, the property's get method won't be called either. (You could override setattr to fix this, but it would be prohibitively expensive.)
Upvotes: 16