Here is a sample of the class structure I am dealing with:
##
# Classes in module::hierarchy (outside of my control)
##
class TopLevelClass:
def __init__(self, args):
self.containedObjects = {}
...
def gather_contained_objects(src):
self.containedObjects = parse_source(src)
...
class ContainedClass:
def __init__(self, args):
self.furtherContainedObjects = {}
...
def gather_further_contained_objects(src):
self.furtherContainedObjects = parse_another_source(src)
...
... And so on.
##
# In my application,
##
import hierarchy
mydata = hierarchy.complexParsingFunction(data_src)
for c_names, c_obj in mydata.containedObjects.items():
for fc_names, fc_obj in c_obj.furtherContainedObjects.items():
if fc_name == "I_WANT_THIS_ONE":
print len(fc_obj.evenDeeperContainedObjects)
...
I am faced with a problem where it would make much sense for an existing object to have a particular method bound to it. I cannot modify the class definition and making a subclass from it will be of no help because the initializing of it occurs inside of the initialization of an encapsulating class (hierarchical structure). I know that Python does allow functions to be bound to instances using the MethodType function in types (see: Adding a Method to an Existing Object Instance ). But, this would mean that I would have to go out and bind my function to every instance. Id rather not re-implement the complexParsingFunction substituting subclassed objects where I need them. So I would like to hear what you would do in this case?
##
# What I would like to do is something on the lines of:
##
@magical_association
class derivedContainedClass(ContainedClass):
def get_certain_derived_data(self):
...
return desired_data
...
for c_name, c_obj in mydata.containedObjects.items():
print c_name, c_obj.get_certian_derived_data()
...
##
# And I really just want to see if I can do this without using
# a simple wrapper function.
##
def get_certain_derived_data(d, cname):
x = d.containedObjects[cname]
...
return desired_data
Its not that I could not just do the wrapper but this is more of an exploration around how to best handle this hierarchical class structure using some of the more advanced features of Python that I am not too familiar with.