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 )
1 Answer
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.
centerx, it is always proportionate toxso you can setcenterxto a value based onxbefore usingcenterxin the function.