0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
A.K.M. Adib
  • 517
  • 1
  • 7
  • 22
  • changed to what? `changed` attribute should be changed to what? – Shivam Jha Jul 02 '20 at 21:10
  • Changed to True – A.K.M. Adib Jul 02 '20 at 21:10
  • Does this answer your question? [Call Python Method on Class Attribute Change](https://stackoverflow.com/questions/48391851/call-python-method-on-class-attribute-change) –  Jul 02 '20 at 21:12
  • 1
    This is an instance attribute, a class attribute is something entirely different. The answer is to make `n` a `@property`, so that code runs when it is assigned. – jasonharper Jul 02 '20 at 21:13
  • Please [edit] the code in your question and show how you intend to _use_ the `changed` attribute. – martineau Jul 02 '20 at 21:25
  • 1
    Does this answer your question? [How do you change the value of one attribute by changing the value of another? (dependent attributes)](https://stackoverflow.com/questions/27308560/how-do-you-change-the-value-of-one-attribute-by-changing-the-value-of-another) – mkrieger1 Jul 02 '20 at 21:27

1 Answers1

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
rdas
  • 20,604
  • 6
  • 33
  • 46