python中的变量更改回调 [英] Callback on variable change in python

查看:153
本文介绍了python中的变量更改回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了周围,但没有找到类似的东西。假设我有很多线程,它们不断读取和更新整数变量 x 。我希望在 x 改变一定幅度(例如500)时运行回调。

I've searched around but didn't find anything like this. Let's say I have an army of threads, that keep reading and updating an integer variable x. I would like a callback for when x changes over a certain margin, let's say 500, to run the callback.

如何在不增加系统负担的情况下完成此操作,例如使线程具有而为真并检查变量是否已更改?性能至关重要。伦理学也是如此。

How can this be done without putting a heavy load on the system, like having a thread that has a while true and checks if the variable has changed? Performance is critical. But so are ethics.

用普通代码是这样的:

x = 10
def runMe():
    print('Its greater than 500!!') 

def whenToRun():
    return x >= 500

triggers.event(runMe, whenToRun)


推荐答案

您想要一个函数(一个 setter ),该函数在变量的值更改时被调用。做到这一点的一种好方法是定义 @property 。它的行为类似于变量,但具有 getter 函数和 setter 函数。

You want to have a function (a "setter") which is called whenever the variable's value changes. A good way to do that is to define a @property. It will behave like a variable, but will have a getter function and a setter function.

然后,在设置器,调用所需的任何回调,这些回调将对更改做出反应。

Then, in the setter, call any callbacks you need, which will react to the change.

这应该可以解决问题:

class ObjectHoldingTheValue:
    def __init__(self, initial_value=0):
        self._value = initial_value
        self._callbacks = []

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new_value):
        old_value = self._value
        self._value = new_value
        self._notify_observers(old_value, new_value)

    def _notify_observers(self, old_value, new_value):
        for callback in self._callbacks:
            callback(old_value, new_value)

    def register_callback(self, callback):
        self._callbacks.append(callback)

然后,您可以执行以下操作:

Then, you can do:

def print_if_change_greater_than_500(old_value, new_value):
    if abs(old_value - new_value) > 500:
        print(f'The value changed by more than 500 (from {old_value} to {new_value})')

holder = ObjectHoldingTheValue()
holder.register_callback(print_if_change_greater_than_500)
holder.value = 7    # nothing is printed
holder.value = 70   # nothing is printed
holder.value = 700  # a message is printed

这篇关于python中的变量更改回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆