In Python, what is the best way of creating an object variable of Object A which is dependent on a variable of Object B and is updated automatically whenever the variable of Object B changes?
Simple example:
class house:
house_size = 100
class room:
room_size = 30
house1 = house()
room1 = room()
house1.house_size = room1.room_size * 10
print house1.house_size #returns 300
room1.room_size = 50
print house1.house_size #still returns 300, but I would like it to return 500
In the example above a relationship between house1.house_size
and room1.room_size
is defined. However, this is only interpreted once. What is the best way to establish a permanent relationship between the two variables to ensure that house1.house_size
is updated automatically whenever room1.room_size
changes subsequently?
Edit:
To clarify, I am looking for a generic solution whereby an object validates whether all its dependencies are still "valid" whenever the value of its object variable is being read. In the example above the object variable house1.house_size
is dependent on room1.room_size
You can think of these dependencies similar to a spreadsheet application: For example, cell A1
might be defined as =B1+B2+B3
and B1
in turn might be defined as =C1*2
. Whenever the value of cell A1
is being read then it will check if any of B1
, B2
or B3
have changed. If so, then the value of A1
will be re-calculated before the value is being returned. So in Python I am looking for an event handler which is triggered whenever the value of house1.house_size
is being read so that its value can be recomputed before being returned.
The answer should be generic enough such that whole dependency trees of objects can be handled whereby each node in the tree checks by itself whether all values of all object variables it depends on are still valid and otherwise recalculates.