python - 捕获python中全局变量值的变化

标签 python python-3.x variables global-variables global

如何检测或捕获 python 中全局变量值的变化

variable = 10
print(variable)
variable = 20 
# Detect changes to the value using a signal to trigger a function

更新 AST 文档 - 很好的介绍 https://greentreesnakes.readthedocs.io/en/latest/

最佳答案

据我所知,在 Python 中一般捕获全局符号的赋值是不可能的(至少在 CPython 中,全局变量存储在 dict 对象的 module 中,两者都是 C 类型,不能被monkey patched)。

这里有一个简单的解决方法,但有一点妥协。使用包装器对象来存储监视的变量,并定义 __setattr__在设置属性之前(或之后)执行您想要执行的任何操作。

class CaptureOnSetAttribute:
    def __setattr__(self, attr, value):
        # our hook to do something
        print(f'set value of {attr} to {value}')
        # actually set the attribute the normal way after
        super().__setattr__(attr, value)


wrapper_object = CaptureOnSetAttribute()

当然,妥协的办法是现在不要写这样的东西:

monitored_global = value

您现在必须写:

wrapper_object.monitored_attribute = value

关于python - 捕获python中全局变量值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675250/

相关文章:

c# - 值设置正确但在使用时为空

Java可变函数参数

python - 扩展类不能被pickle

python - 导入包含 'import' 命令的模块有什么好处或坏处?

python - 我如何确保为层次结构中的每个类调用一个方法(一次,如果存在)?

python-3.x - Matplotlib动画报错 "Requested MovieWriter (ffmpeg) not available"

python - 如何获取 YouTube 通知

python - 如何使用 python API 为 Mechanical Turk 中的批处理设置多个资格标准

javascript - 在 Javascript 数组中引用变量

python - 如何合并 2 个 pandas 系列?