python - 为什么属性包装的成员列表显示意外的值?

标签 python python-2.7 properties python-decorators

以这个简单的示例类为例:

class vec:
   def __init__(self,v=(0,0,0,0)):
       self.v = list(v)

   @property
   def x(self):
       return self.v[0]

   @x.setter
   def set_x(self, val):
       self.v[0] = val

...以及这个用法:

>> a = vec([1,2,3,4])
>> a.v
[1,2,3,4]
>> a.x
1
>> a.x = 55
>> a.x
55
>> a.v
[1,2,3,4]

为什么成员数组(具体来说,self.v[0])和报告的属性值不一致?如果它不在 self.v 中,那么更改后的属性值来自哪里?

最佳答案

您应该使用新式类。并且 setter 的名称应该是 x,而不是 set_x

class vec(object): # <-----
   def __init__(self,v=(0,0,0,0)):
       self.v = list(v)

   @property
   def x(self):
       return self.v[0]

   @x.setter
   def x(self, val): # <--------
       self.v[0] = val

根据property documentation :

Return a property attribute for new-style classes (classes that derive from object).

如果您不使用新式类,a.x = ... 会创建一个新属性 x,而不是调用 setter。

关于python - 为什么属性包装的成员列表显示意外的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971646/

相关文章:

python - PyCharm 右键单击​​文件夹 -> 上下文菜单 : how to change from "hold down" to "toggle"?

python - Python 字典中有一个嵌套列表

python - 在 ubuntu 16.04 中安装 Python 2.7.6

python - Python 2.7 中的 MySQLdb 错误处理

java - 属性是将特定参数和数据输入 java 程序的最佳方式吗?

python - 堆叠水平条形图,图例位于图内。我怎样才能让这个情节更明显

Python:如何通过一些字符串连接将每个字符串拆分为新行

python - 从美分到美元的数字格式

java - 使用反射动态保存一个类中的所有字段? ("<FieldName>","<FieldValue>")

c# - 有没有理由拥有没有 setter/getter 的属性(property)?