Detecting class attribute value change and then changing another class attribute

亡梦爱人 提交于 2021-02-17 07:10:30

问题


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

When the n class attribute changes, I want the changed class attribute to be changed to True.


回答1:


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


来源:https://stackoverflow.com/questions/62705053/detecting-class-attribute-value-change-and-then-changing-another-class-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!