1

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
  • 2
    Does this 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. Commented May 16, 2021 at 11:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.