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 value
property totally breaks the semantics of +=
operator.
Override the __iadd__
magic method.
You need to do that because +=
means "take the value and add five, then set that as the result". If you want it to know that the value isn't really the value, you need to change the semantics of the +=
operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With