No, this is not possible, at least not directly in the way you're talking about it. Each instance has an independent set of instance variables, so there's no central place where you can set or change a value such that all of the existing instances will reflect the change.
However, you might be interested in properties, which is a way you can write the same code you would use to access a variable but have it call a function instead. Just for example, if you wanted to make a class that appears to have two variables, a
and b
, such that b
is always one more than a
:
class Example: def __init__(self, a): self.a = a @property def b(self): return self.a + 1
With this, you can do the following:
>>> instance = Example(1)>>> instance.a, instance.b(1, 2)>>> instance.a = 5>>> instance.a, instance.b(5, 6)
It's also possible to allow setting a property by writing code like
class Example: def __init__(self, a): self.a = a @property def b(self): return self.a + 1 @b.setter def set_b(self, value): self.a = value - 1
Other things along these lines are possible as well; you can find a lot of information about this elsewhere online.
In your case, you may want to define either your x
or your y
or both as properties which check a central location (maybe a class variable or module-level variable) for some value and compute the property value based on that centrally stored value. Perhaps you might want setter methods that would manipulate that centrally stored value as well.