检测类属性值更改,然后更改另一个类属性

时间:2020-07-02 21:09:02

标签: python class oop

比方说我有一个叫做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

n类属性更改时,我希望将changed类属性更改为True

1 个答案:

答案 0 :(得分:1)

可以正确使用@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)

返回:

8
9
True
相关问题