0

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 Answer 1

2

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):
              ^^^^^^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.