Detecting change in the value of python variables

2020-02-13 02:10发布

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.

5条回答
smile是对你的礼貌
2楼-- · 2020-02-13 02:33

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
查看更多
做个烂人
3楼-- · 2020-02-13 02:34

This package may be helpful.

查看更多
一纸荒年 Trace。
4楼-- · 2020-02-13 02:36

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楼-- · 2020-02-13 02:39

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

查看更多
我想做一个坏孩纸
6楼-- · 2020-02-13 02:46

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
查看更多
登录 后发表回答