将方法附加到Python中封装在其他对象中的现有对象

时间:2014-03-07 05:13:21

标签: python hierarchy python-decorators

以下是我正在处理的类结构示例:

##
# 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)
...

我遇到了一个问题,即现有对象有一个特定的方法绑定它是有意义的。我无法修改类定义并从中创建子类将无济于事,因为它的初始化发生在封装类(层次结构)的初始化中。我知道Python确实允许使用类型中的MethodType函数将函数绑定到实例(请参阅:Adding a Method to an Existing Object Instance)。但是,这意味着我必须出去将我的函数绑定到每个实例。我宁愿不重新实现complexParsingFunction替换我需要它们的子类对象。所以我想听听你在这种情况下会做些什么?

##
# 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

这不是我不能只做包装器,而是更多的探索如何使用我不太熟悉的Python的一些更高级的功能来最好地处理这种分层类结构。

0 个答案:

没有答案