Consider the following simple example class, which has a property that exposes a modified version of some internal data when called:
class Foo(object):
def __init__(self, value, offset=0):
self._value = value
self.offset = offset
@property
def value(self):
return self._value + self.offset
@value.setter
def value(self, value):
self._value = value
The value.setter works fine for regular assignment, but of course breaks down for compound assignment:
>>> x = Foo(3, 2) >>> x.value 5 >>> x.value = 2 >>> x.value 4 >>> x.value += 5 >>> x.value 11
The desired behavior is that x.value += 5 should be equivalent to x.value = x._value + 5, as opposed to x.value = x.value + 5. Is there any way to achieve this (with the property interface) purely within the Foo class?
@ezod, there is no direct way to do what you’re asking for, even with the descriptors protocol.
That kind behaviour of
valueproperty totally breaks the semantics of+=operator.