我有两个包含列表的属性。每当此列表中的任何项目发生更改时,我都希望另一个列表自行更新。这包括声明obj.myProp[3]=5。现在,该语句调用 getter 函数来获取整个列表,从列表中获取第三个项目,并将其设置为 5。myProp列表已更改,但第二个列表永远不会更新。
class Grid(object):
    def __init__(self,width=0,height=0):
        # Make self._rows a multi dimensional array
        # with it's size width * height
        self._rows=[[None] * height for i in xrange(width)]
        # Make `self._columns` a multi dimensional 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 columns 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
示例运行:
>>> 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]]
如果您查看最后三行,这就是实际问题发生的地方。我将子列表的第一项设置为 3,但从foo.columns不更新自身以将 3 放入其列表中。
简而言之,我如何制作一个始终更新另一个变量的变量,即使它的子项正在更改?
我正在使用 Python 2.7