Detecting change in the value of python variables

限于喜欢 提交于 2019-11-29 12:21:16
Jochen Ritzel

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.

Vaughn Cato

This package may be helpful.

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