Mam dwie właściwości, które przechowują listy. ilekroć jakikolwiek element na tej liście ulegnie zmianie, chciałbym aby druga lista aktualizowała się sama. dotyczy to również instrukcji obj.myProp [3] = 5. teraz, ta instrukcja wywołuje funkcję getter, aby pobrać całą listę, pobiera trzeci element z listy i ustawia go na 5. lista myProp zmienia się, ale druga lista nigdy nie jest aktualizowana.python: jak mieć właściwość i funkcję ustawiającą, która wykrywa wszystkie zmiany, które mają wartość
tutaj jest mój kod
class grid(object):
def __init__(self,width=0,height=0):
#make self._rows a multi demensional array
#with it's size width*height
self._rows=[ [None]*height for i in xrange(width) ]
#make self._columns a multi demensional array
#with it's size height*width
self._columns=[ [None]*width for i in xrange(height) ]
@property
def rows(self):#getting the rows of the array
return self._rows
@rows.setter
def rows(self,value):#when the rows are changed, the collumns are updated.
self._rows=value
self._columns=self._flip(value)
@property
def columns(self):#getting the columns of the array
return self._columns
@columns.setter
def columns(self,value):#when the columns are changed, the rows are updated
self._columns=value
self._rows=self._flip(value)
@staticmethod
def _flip(args):#this flips the array
ans=[ [None]*len(args) for i in xrange(len(args[0])) ]
for x in range(len(args)):
for y in range(len(args[0])):
ans[y][x] = args[x][y]
return ans
i tutaj jest przykładem run.
>>> foo=grid(3,2)
>>> foo.rows
[[None, None], [None, None], [None, None]]
>>> foo.columns
[[None, None, None], [None, None, None]]
>>> foo.rows=[[1,2,3],[10,20,30]]
>>> foo.rows
[[1, 2, 3], [10, 20, 30]]
>>> foo.columns
[[1, 10], [2, 20], [3, 30]]
>>> foo.rows[0][0]=3
>>> foo.rows
[[3, 2, 3], [10, 20, 30]]
>>> foo.columns
[[1, 10], [2, 20], [3, 30]]
jeśli spojrzysz na ostatnie trzy linie, to tutaj pojawia się rzeczywisty problem. Ustawiłem pierwszy element podlisty na trzy, ale foo.columns nigdy się nie aktualizuje, aby umieścić 3 na liście.
Krótko mówiąc, w jaki sposób utworzyć zmienną, która zawsze aktualizuje inną zmienną, nawet w przypadku zmiany podelementu.
Używam Pythona 2.7