[对象属性在Python中具有额外的功能

问题描述 投票:0回答:1

我正在基于@property的思想来开发描述符。我想了解的是,是否有任何方法可以轻松地将属性的行为扩展到设置/获取之外。

具体示例:我正在与设备通信,并且希望拥有一个可以设置/获取/更新的属性。这样,当我set时,我将新值传递给设备,并将其存储在缓存中。当我get时,我检索了缓存的值。当我update时,将重新询问设备的值。这样,可以避免与设备不必要的通信,除非明确触发。

我不知道是否缺少一种可能是直接解决方案的模式。一种选择是在set中使用特殊值时使缓存无效,但是我认为假设特定值触发更新不是一个好主意。

python caching properties descriptor
1个回答
0
投票

我仍然不了解您的getterupdater之间的区别,但是这里有一些示例代码,实现了存储先前变量值的缓存。也许这可以帮助您找到所需的内容。

class A:
    def __init__(self):
        self._a_cache = [1]

    @property  # <- this defines a.getter
    def a(self):
        return self._a_cache[-1]

    @a.setter
    def a(self, value):
        self._a_cache.append(value)

    def undo(self):
        if len(self._a_cache) > 1:
            self._a_cache.pop()
        else:
            print('No previous values')

    def update(self):
        # what is supposed to happen here as opposed to the getter?
        pass


var = A()
print(var.a)

var.a = 10
print(var.a)

var.undo()
print(var.a)

var.update()
# ?
© www.soinside.com 2019 - 2024. All rights reserved.