我已經看到了這個答案非常類似的問題:在類對象中,如何在只更改列表中的一個條目時自動更新屬性?
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自動更新,當我改變列表中只有一個項目?