Python setter 不会改变变量 [英] Python setter does not change variable

查看:49
本文介绍了Python setter 不会改变变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能我不完全理解 python 中属性的概念,但我对我的 Python 程序的行为感到困惑.

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

我有一堂这样的课:

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

我期望的是,调用 MyClass.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

我在编写属性时犯了错误还是这真的是正确的行为?我知道我不应该调用 my_class._value 来读取值,但无论如何我希望它应该可以工作.我使用的是 Python 2.7.

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.

推荐答案

该类应该继承 object 类(换句话说,该类应该是 new-style class) 以使用 value.setter.否则不会调用 setter 方法.

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

这篇关于Python setter 不会改变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆