【发布时间】:2016-09-29 15:56:25
【问题描述】:
我已经看到了一个非常相似的问题的答案:
In class object, how to auto update attributes?
我把代码贴在这里:
class SomeClass(object):
def __init__(self, n):
self.list = range(0, n)
@property
def list(self):
return self._list
@list.setter
def list(self, val):
self._list = val
self._listsquare = [x**2 for x in self._list ]
@property
def listsquare(self):
return self._listsquare
@listsquare.setter
def listsquare(self, val):
self.list = [int(pow(x, 0.5)) for x in val]
>>> c = SomeClass(5)
>>> c.listsquare
[0, 1, 4, 9, 16]
>>> c.list
[0, 1, 2, 3, 4]
>>> c.list = range(0,6)
>>> c.list
[0, 1, 2, 3, 4, 5]
>>> c.listsquare
[0, 1, 4, 9, 16, 25]
>>> c.listsquare = [x**2 for x in range(0,10)]
>>> c.list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
在这段代码中,当我使用以下方法更新列表时:
>>> c.list = [1, 2, 3, 4]
c.listsquare 将相应更新:
>>> c.listsquare
[1, 4, 9, 16]
但是当我尝试时:
>>> c.list[0] = 5
>>> c.list
[5, 2, 3, 4]
Listsquares 未更新:
>>> c.listsquare
[1, 4, 9, 16]
当我只更改列表中的一项时,如何使 listsquare 自动更新?
【问题讨论】:
标签: python class attributes