How is it possible that the rectangle-object listens to the Points attributes x and y and if they change, the rectangle-object recalculates the area?
If I do it with setters and getters, every time I access the area attribute, the area will be recalculated. If the calculation is very expensive (I do some more stuff here) this is not an optimal solution for me. Is it possible to listen to the Points, only recalculating the area if they change?
I have a class called Rectangle and a class called Point:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle(object):
def __init__(self, points=None):
self.points = [] if points is None else points
self.area = self.calc_area()
def calc_area(self):
return (self.points[0].x - self.points[1].x) * (self.points[0].y - self.points[1].y)
Then I create two points and a rectangle with the two points:
# create the points:
points = list()
points.append(Point(0,0))
points.append(Point(1,1))
# create the rectangle:
rect = Rectangle(points)
print(rect.area)
Now I change the coordinates of the first point:
# change the points coordinates:
points[0].x = 0.5
points[0].y = 0.5
# Now the area should be recalculated.
print(rect.area)