Search code examples
pythonpython-3.xgetter-setter

Minus equal operator doesnt call property setter python


I have my code setup this way:

class Test():
    def __init__(self):
        self.offset = [0,0]

    @property
    def offset(self):
        return self._offset

    @offset.setter
    def offset(self,offset):
        print("set")
        self._offset = offset

test = Test()
test.offset[1] -= 1

but the setter is being called only once even though I am changing my variable twice, anyone is able to help ?


Solution

  • test.offset[1] -= 1
    

    This line of your code is calling the getter not the setter. You get the list from the test object and then you alter its contents.

    Same as if you wrote:

    v = test.offset   # get the list
    v[1] -= 1         # alter the contents of the list