首页 > 解决方案 > Stringtoknow="value" 我想在变量 stringtoknow 在 python 中更改值时运行函数

问题描述

我是 python 新手在 python 中,这是我的代码

Stringtoknow = "value"

#some code

def onchange():
    print("the value change")

Stringtoknow = "new value"

# run the onchange function

我想要在 Stringtoknow 变量更改时将运行 onchange 函数的代码

标签: python

解决方案


如果您可以将变量放在类实例中,那么我们可以做到。

实例变量很好,因为我们可以完全控制它们。我们总是可以控制分配给他们时发生的事情。这正是属性的用途。

class Example:

    def __init__(self):
        self._impl = "value"

    @property
    def Stringtoknow(self):
        return self._impl

    @Stringtoknow.setter
    def Stringtoknow(self, v):
        self._impl = v
        print("the value changed")

example = Example()
print(example.Stringtoknow)
example.Stringtoknow = "new value"
print(example.Stringtoknow)

推荐阅读