简体   繁体   中英

How to execute code on a change in a instance variable?

I have an instance variable from a class and I want to execute some code when there is a change in my variable.

I'm aware of the property and Observer pattern event handling but I don't think it helps in my case.

Example:

class Thing:
  def __init__(self):
      self.thing = []
      self.thing2 = ""
  def code_that_executes(self):
      self.thing2 = self.thing[0]
s = Thing()
s.thing.append("Something") #The event 

You can implement setattr on your class. Here is an example:

class A:
    def __init__(self):
        self.A = 5
    def __setattr__(self, name, value):
        if name == "A":
            print("A has changed to: {0}".format(value))
Now when you have an object `foo = Foo()` and call `foo.bar = 5` you get the result:
 bar changed to 5 

See https://docs.python.org/3/reference/datamodel.html#object. setattr

Note:This will print during the init call as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM