开发者

Detecting change in the value of python variables

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, Sct开发者_如何学编程iptA has to call a method to handle that change.


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


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


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)


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜