Detecting change in the value of python variables

↘锁芯ラ 提交于 2019-11-28 06:01:33

问题


Is there some way to call a function each-time the value of a variable changes, in python?

Something like a listener, perhaps?

Specifically, I'm referring to the case where only the variable is shared between scripts like a GAE-Session. (Which uses Cookies, Memcache, etc to share data)

Example: ScriptA & ScriptB, share a session variable. When Script B changes it, SctiptA has to call a method to handle that change.


回答1:


Use properties. Only mutable values can change to begin with.

class Something(object):
    @property
    def some_value(self):
        return self._actual
    @some_value.setter
    def some_value(self, value):
        print ("some_value changed to", value)
        self._actual = value



回答2:


If the variable is a class attribute, you may define __setattr__ in the class.




回答3:


This package may be helpful.




回答4:


You Probably need extend type "int" or "float", and override the function "setattr", make it to response in your own way.

class MyInt(int):
    ...
    def __setattr__(self, attr, val):
        ...
        super(MyInt, self).__setattr__(attr, val)
        ...

var = MyInt(5)



回答5:


For this case (And I can't believe im saying the words) sounds like situation for setters

def set_myvar(x):
    my_var = x
    some_function()
    return my_var


来源:https://stackoverflow.com/questions/7540443/detecting-change-in-the-value-of-python-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!