Python3:如何改善复杂的类层次结构以更好地访问埋在其中的某些对象?

时间:2018-10-24 18:21:57

标签: python design-patterns

我有一个复杂的类层次结构,其中的类彼此相似,但是每个类都包含一堆或多或少复杂的有状态变量。为了给您留下深刻的印象,请看一下这个最小的工作示例:

class OptVar:
    """
    Complicated stateful variable
    """
    def __init__(self, **kwargs):
        self.parameters = kwargs


class OptVarContainer:
    """
    Class which contains several OptVar objects and nested OptVarContainer
    classes. Is responsible for OptVar management of its sub-OptVarContainers
    with their respective OptVar objects.
    """
    def __init__(self, **kwargs):
        for (key, value_dict) in kwargs.items():
            setattr(self, key, OptVar(**value_dict))


class C(OptVarContainer):
    """
    Specific implementation of class OptVarContainer
    """
    def __init__(self):
        super(C, self).__init__(
                **{"my_c_a": {"c1": 1, "c2": 2},
                   "my_c_b": {"c3": 3, "c4": 4}})


class B(OptVarContainer):
    """
    Specific implementation of class OptVarContainer
    """
    def __init__(self):
        super(B, self).__init__(**{"b": {"1": 1, "2": 2}})
        self.c_obj = C()


class A(OptVarContainer):
    """
    Specific implementation of class OptVarContainer
    """
    def __init__(self):
        super(A, self).__init__(
                **{"a1": {"1": 1, "2": 2},
                   "a2": {"a": "a", "b": "b"}})
        self.b_obj = B()


def main():
    # creating OptVarContainer with some nested OptVarContainers.
    my_a_obj = A()
    # It is intended behaviour to access the OptVar objects via
    # scoping within the class hierarchy.
    print(my_a_obj.b_obj.b.parameters)
    my_a_obj.b_obj.b.parameters["2"] = 3
    print(my_a_obj.b_obj.b.parameters)
    print(my_a_obj.b_obj.c_obj.my_c_a.parameters["c1"])
    my_a_obj.b_obj.c_obj.my_c_a.parameters["c1"] = 6
    print(my_a_obj.b_obj.c_obj.my_c_a.parameters)
    # Two major problems:
    # a) Serialization (with compatibility between different versions)
    # b) Access to all OptVar objects at once


if __name__ == "__main__":
    main()

现在的问题是:如何最好地访问OptVar对象。我已经考虑过要使用某种池对象,并在类层次结构中使用某些代理来链接到池。此池不应为单例,因为一次可以管理多个池。到目前为止,我自己的代码中的OptVar变量是通过一些Python魔术来访问的,并以递归方式遍历类,从而通过维护id列表避免了无限循环。这非常丑陋,只是暂时的。

我知道没有针对此设计问题的独特解决方案,但我需要您提供进一步的意见。

此问题的完整内容为here,但经过一些讨论,我分离了设计部分。

0 个答案:

没有答案