简体   繁体   English

减等于运算符不调用属性设置器 python

[英]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?但是即使我两次更改我的变量,setter 也只被调用一次,有人能帮忙吗?

test.offset[1] -= 1

This line of your code is calling the getter not the setter.这行代码调用的是 getter 而不是 setter。 You get the list from the test object and then you alter its contents.您从测试 object 中获取列表,然后更改其内容。

Same as if you wrote:就像你写的一样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM