1

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.

6

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

You wouldn't need a property for changed.
Added that to keep it consistent with what OP is expecting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.