Python setter does not change variable

馋奶兔 提交于 2019-12-12 04:32:16

问题


May be I do not completely understand the concept of properties in python, but I am confused by the behaviour of my Python program.

I have a class like this:

class MyClass():
  def __init__(self, value):
    self._value = value

  @property
  def value(self):
    return self._value

  @value.setter
  def value(self, value):
    self._value = value

What I would expect is, that calling MyClass.value = ... changes the content of _value. But what actually happened is this:

my_class = MyClass(1)
assert my_class.value == 1 # true
assert my_class._value == 1 # true

my_class.value = 2

assert my_class.value == 2 # true
assert my_class._value == 2 # false! _value is still 1

Did I make a mistake while writing the properties or is this really the correct behaviour? I know that I should not call my_class._value for reading the value, but nevertheless I would expect that it should work, anyway. I am using Python 2.7.


回答1:


The class should inherit object class (in other word, the class should be new-style class) to use value.setter. Otherwise setter method is not called.

class MyClass(object):
              ^^^^^^


来源:https://stackoverflow.com/questions/24534861/python-setter-does-not-change-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!