自动跟踪属性值

时间:2018-08-07 16:22:34

标签: python

假设我有一个由定义的类:

class Wall(object):
    def __init__(self, color):
        self.color = color

我想自动跟踪颜色过渡。 就是说,如果我按如下方式实例化课程:

wall = Wall('red')

然后更改颜色:

wall.color = 'green'

我想自动获取列表

['green', 'red']

创建后,如果我继续执行以下操作:

wall.color = ['yellow']

我获得了清单:

['yellow', 'green']

以此类推。

到目前为止我尝试过的方法不起作用:

class Wall(object):

def __init__(self, color):
    self.color = color
    self._last_two_colors = [self.color, None]

def change_color(self, color):
    self._last_two_colors[1] = self._last_two_colors[0]
    self._last_two_colors[0] = self.color
    return self._last_two_colors

我的初始版本,不幸的是无法正常工作:

class Wall(object):

    def __init__(self, color):
        self._last_two_colors = []
        self.color = color

    @property
    def last_two_colors(self):
        return self._last_two_colors

    @last_two_colors.setter
    def last_two_colors(self):
        self._last_two_colors = [self.color]+self._last_two_colors
        self._last_two_colors = self._last_two_colors[:2]
        return self._last_two_colors

应该注意,我不希望调用change_color方法,只要更新颜色,就必须自动调用该方法。 有任何想法吗? 预先感谢。

2 个答案:

答案 0 :(得分:2)

就像我的评论中所述,这是第一个不完美的版本:

In [14]: class Wall(object):
...: 
...:     def __init__(self, color):
...:         self.__last_two = [color, color]
...:         self.__color = color
...:     
...:     @property
...:     def color(self):
...:         return self.__color
...:     
...:     @color.setter
...:     def color(self, new_val):
...:         self.__color = new_val
...:         self.__last_two.pop(0)
...:         self.__last_two.append(new_val)
...:         print(self.__last_two)
...:  

In [15]: x = Wall(1)

In [16]: x.color
Out[16]: 1

In [17]: x.color = 2
[1, 2]

In [18]: x.color = 3
[2, 3]

In [19]: x.color = 4
[3, 4]

答案 1 :(得分:0)

使用property()

class Wall(object):

    def __init__(self, color):
        self._color = color
        self._color_transitions = [color]

    @property
    def color(self):
        """I'm the 'color' property."""
        return self._color

    @color.setter
    def color(self, value):
        if len(self._color_transitions) > 1:
            self._color_transitions.pop(0)
        self._color_transitions.append(value)
        self._color = value

    @property
    def color_transitions:
        return self._color_transitions