0

How to assign values to a slice of some @property of a class, which happens to be a list or numpy.ndarray, so that it's setter is called? Now it seems that assignment to a slice calls only getter. I cannot understand how a slice is handled under the hood in such case. Example code:

class MyClass:
  def __init__(self, a):
    self.a = a
    self._a = self.a

  @property
  def a(self):
    return self._a

  @a.setter
  def a(self, v):
    print("I'm called")
    self._a = v

A = MyClass([1, 2, 3])
# prints "I'm called"
A.a = [4, 5, 6]
# prints "I'm called"
A.a[1] = 0
# does not print anything

How to make A.a[1] = 0 print "I'm called"?

Cos_ma
  • 75
  • 9
  • Well, it is slightly different. It does not call setter but instead makes a determined action. I see one solution based on this - subclass list with additional attribute which will point to its parent and then call a setter from the parent inside `__setitem__`. But it seems a bit hacky, so I wonder -- is there a better solution? – Cos_ma May 05 '18 at 10:10
  • The only other solution is to write a setter method in `MyClass` and then do `A.set_a(1, 0)` instead of `A.a[1] = 0`. – Aran-Fey May 05 '18 at 10:13
  • Thanks for the proposed solution but it does not disprove my point that the question is not a duplicate of the one you are referencing, so could you remove your mark? – Cos_ma May 05 '18 at 10:16
  • Sorry, no. You're trying to run some code when a list item is changed. The other question is trying to run some code when a dict item is changed. Having to pass a reference to `self` to the `MyList` class is a trivial difference that doesn't make your question different from the other question. – Aran-Fey May 05 '18 at 10:21

0 Answers0