yeah, I see what you mean, thanks, so is there any way to check if such reassignment happened in class B's constructor?
Answering a question from the comments, this can certainly be done. It's not foolproof, in the sense that a programmer can go out of their way to cheat your system, but they have to do so on purpose.
We just need to make a
a property.
class A:
def __init__(self):
self._a = 1
self.was_a_changed = False
@property
def a(self):
return self._a
@a.setter
def a(self, x):
self._a = x
self.was_a_changed = True
class B(A):
def __init__(self):
self.a = 1
class C(A):
pass
obj_a = A()
obj_b = B()
obj_c = C()
print(obj_a.was_a_changed) # False
print(obj_b.was_a_changed) # True
print(obj_c.was_a_changed) # False
Now a
isn't a real value; it's a property which is backed by the actual value _a
. But if a subclass reassigns a
, it'll make a note so that we can check whether it's been touched later.
If someone wants to cheat your system, they can always assign directly to self._a
rather than self.a
, but that would be unidiomatic Python to assign to a private you don't own anyway.