I'm writing a program that consists of a 'master' object, which keeps track of and manipulates many smaller objects. Here is a simplified example:
class My_obj: def __init__(self, a): self.a = a def set_a(self, a): self.a = a def get_a(self): return self.a class Master: def __init__(self, list_): self.obj_list =  for value in list_: obj = My_obj(value) self.obj_list.append(obj) m = Master([0, 1, 2]) # How do I get (or set) the value of <a> from one of the My_obj instances # within the new Master object?
I know of two ways to do this. The first is to add a method to
Master that returns the requested object:
def get_obj(self, index): return self.obj_list[index]
I could then call any method directly on the object. However, this seems dangerous: if subsequent code deletes the returned object, and then something in
Master tries to look it up, the program would crash.
EDIT: Turns out it would not crash, but still a problem; see comments.
The second way would be to wrap each method with a corresponding method in
def set_a(self, index, a): self.obj_list[index].set_a(a) def get_a(self, index): return self.obj_list[index].get_a()
This seems redundant, and would get quite tedious in a more complicated scenario.
Does anyone know of a better way to access these methods?