Skip to content Skip to sidebar Skip to footer

Detecting Class Attribute Value Change And Then Changing Another Class Attribute

Let's say I have a class called Number class Number(): def __init__(self,n): self.n=n self.changed=None a = Number(8) print(a.n) #prints 8 a.n=9 print(a.n) #prints 9 Wh

Solution 1:

Possible with proper use of @propety

classNumber():
  def__init__(self,n):
    self._n=n
    self._changed=None  @propertydefn(self):
      return self._n

  @propertydefchanged(self):
      return self._changed

  @n.setterdefn(self, val):
      # while setting the value of n, change the 'changed' value as well
      self._n = val
      self._changed = True

a = Number(8)
print(a.n) #prints 8
a.n=9print(a.n) #prints 9print(a.changed)

Returns:

89True

Post a Comment for "Detecting Class Attribute Value Change And Then Changing Another Class Attribute"