Stringtoknow="value" i want to run function when variable stringtoknow changes value in python

Viewed 44

Im new to python In python here is my code

Stringtoknow = "value"

#some code

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

Stringtoknow = "new value"

# run the onchange function

I want the code that will run onchange function when Stringtoknow variable changes

3 Answers

If you can put the variable inside of a class instance, then we can do it.

Instance variables are nice because we have total control over them. We can always control what happens when assigning to them. This is exactly what properties are for.

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)

This doesn't exactly answer your question, but consider using a setter. If you do that, this becomes trivial

Stringtoknow = ''

def update_string_to_know(new_string):
    Stringtoknow = new_string
    print("the value change")

update_string_to_know("new value")

Without more context, this seems like a reasonable way of accomplishing the ask

Based on Silvio Mayolo's answer, I think comparing origin value with final value is also needed.


class StringValueWatcher():

    def __init__(self):
        self._final = self._origin = 'initial'

    @property
    def string_value(self):
        return self._final

    @string_value.setter
    def string_value(self, v):
        self._origin = self._final
        self._final = v
        if self._origin != self._final:
            self.on_change()

    def on_change(self):
        print(f"value changed from {self._origin} to {self._final}")


e = StringValueWatcher()
print(e.string_value)        # initial value
# initial
e.string_value = "initial"   # not change
e.string_value = "new_value" # changed
# value changed from initial to new_value



Related