Detecting class attribute value change and then changing another class attribute

后端 未结 1 1764
面向向阳花
面向向阳花 2021-01-29 07:09

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(         


        
相关标签:
1条回答
  • 2021-01-29 07:52

    Possible with proper use of @propety

    class Number():
      def __init__(self,n):
        self._n=n
        self._changed=None
    
      @property
      def n(self):
          return self._n
    
      @property
      def changed(self):
          return self._changed
    
      @n.setter
      def n(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=9
    print(a.n) #prints 9
    print(a.changed)
    

    Returns:

    8
    9
    True
    
    0 讨论(0)
提交回复
热议问题