I was wondering, how to do python class like pygame.Rect. What i mean by that is how to make a class where, when you change one variable, the others change as well ( with pygame Rect you can change for example variable x and automaticly variable centerx changes to adapt )
Asked
Active
Viewed 63 times
1
-
2Does [this](https://stackoverflow.com/questions/6190468/how-to-trigger-function-on-value-change) answer your question? You can also change the variable in the function before you use it. For example, a variable like `centerx`, it is always proportionate to `x` so you can set `centerx` to a value based on `x` before using `centerx` in the function. – Orbital May 16 '21 at 11:43
1 Answers
1
You're talking about property setters and getters! Here's a toy example with a circle:
import math
class Circle:
def __init__(self, radius):
self._radius = radius
self.update_from_radius()
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, val):
self._radius = val
self.update_from_radius()
def update_from_radius(self):
self.area = self._radius*self._radius*math.pi
self.circumference = 2*self._radius*math.pi
self.diameter = 2*self._radius
c = Circle(4)
print(c.area) >>> 50.26548245743669
c.radius = 8
print(c.area) >>> 201.06192982974676
If you want to learn more, have a look here, which gives a pretty good explanation.

Lucas Ng
- 671
- 4
- 11