Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property setters for compound assignment?

Tags:

python

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?

like image 598
ezod Avatar asked Oct 10 '22 10:10

ezod


2 Answers

@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.

like image 172
Zaur Nasibov Avatar answered Oct 13 '22 01:10

Zaur Nasibov


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.

like image 24
Katriel Avatar answered Oct 13 '22 01:10

Katriel