Suppose I have a single instance of a master object that contains a set of parameters, then multiple instances of slave objects that should be able to access and modify the attributes of the master. In my particular case the slaves are wxPython GUI objects, where there might be multiple GUI controls that can modify the same parameter.
Obviously this is trivial if I explicitly refer to master.parameter when the slave wants to update it. However I would really prefer not to have to do this, since it would require me to write different functions to handle events from each slave object.
I'm currently doing something like this, with the master having separate get_value and set_value methods for each property:
class Master(object):
def __init__(self):
self.value = 0
def get_value(self):
return self.value
def set_value(self,value):
self.value = value
class Slave(object):
def __init__(self,getfunc,setfunc):
self.getfunc = getfunc
self.setfunc = setfunc
def update(self,value):
self.setfunc(value)
def run():
master = Master()
slave = Slave(master.get_value,master.set_value)
print "\nMaster: %i\nSlave: %i" %(master.value,slave.getfunc())
slave.update(1)
print "\nMaster: %i\nSlave: %i" %(master.value,slave.getfunc())
if __name__ == "__main__":
run()
What I really want to be able to do is set something like slave.bound_value, which would behave like a pointer to master.value, so that when any slave modifies its bound_value then the corresponding attribute of master is updated. I'm fully aware that Python doesn't support pointers, but I was wondering if there's a nice Pythonic way to achieve the same thing?