列表中的 Python 属性 [英] Python property on a list
问题描述
我是 Python 新手,我刚刚发现了这些属性.当我在一个简单的变量上尝试它时它工作得很好,但我不能让它在列表上工作.执行下面的代码时,它将调用两次 getter 而不是 setter.我知道在我的例子中,属性没有附加值,但它是为了简化.
I am new to Python and I just discovered the properties. It works just fine when I try it on a simple variable but I cannot make it work on a list. When executing the code below it will call two times the getter and not the setter. I know that in my example the property has no added value but it is to simplify.
class C:
def __init__(self):
self._x = [1, 2, 3]
@property
def x(self):
print("getter")
return self._x
@x.setter
def x(self, value):
print("setter")
self._x = value
c = C()
c.x[1] = 4
print(c.x[1])
有人知道我做错了什么吗?
Does anybody have an idea about what I'm doing wrong ?
推荐答案
setter/getter 仅在直接获取或设置属性时使用:
The setter/getter are only used if you directly get or set the property:
c.x # getter
c.x = [1,2,3] # setter
如果您修改属性中的元素,则会获取该属性,然后设置相应的元素.你的例子相当于
If you modify an element in the property you get the property and then set the corresponding element. Your example is equivalent to
d = c.x # getter again
d[1] = 4
您也可以使用 __getitem__
和 __setitem__
直接允许设置和获取特定项目.
You could also use __getitem__
and __setitem__
to directly allow setting and getting specific items.
class C:
def __init__(self):
self._x = [1, 2, 3]
@property
def x(self):
print("getter")
return self._x
@x.setter
def x(self, value):
print("setter")
self._x = value
def __getitem__(self, idx):
print("getitem")
return self._x[idx]
def __setitem__(self, idx, value):
print("setitem")
self._x[idx] = value
>>> c = C()
>>> c[1] = 3
setitem
>>> c.x
getter
[1, 3, 3]
>>> c[2]
getitem
3
这篇关于列表中的 Python 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!