smilestack
smilestack

Reputation: 33

Python setter does not change variable

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.

Upvotes: 0

Views: 673

Answers (1)

falsetru
falsetru

Reputation: 368964

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):
              ^^^^^^

Upvotes: 2

Related Questions