python - 如何在 python 中以优雅的方式动态创建对象?

标签 python

我想将两个类合并到一个组合中。这两个类将继续单独使用,我不想修改它们。 出于某些原因,我想让我的复合类创建对象。我正在考虑类似下面代码的东西(这只是一个例子),但我认为它很复杂,我不太喜欢它。我想它可以通过一些我忽略的技术和技巧来改进。

请注意,组合旨在管理许多具有不同构造函数签名的不同类。

为了改进此代码,有什么建议?

class Parent:
    def __init__(self, x):
        self.x = x

class A(Parent):
    def __init__(self, x, a="a", b="b", c="c"):
        Parent.__init__(self, x)
        self.a, self.b, self.c = a, b, c

    def do(self):
        print self.x, self.a, self.b, self.c

class D(Parent):
    def __init__(self, x, d):
        Parent.__init__(self, x)
        self.d = d

    def do(self):
        print self.x, self.d

class Composite(Parent):
    def __init__(self, x, list_of_classes, list_of_args):
        Parent.__init__(self, x)
        self._objs = []
        for i in xrange(len(list_of_classes)):
            self._objs.append(self._make_object(list_of_classes[i], list_of_args[i]))

    def _make_object(self, the_class, the_args):
        if the_class is A:
            a = the_args[0] if len(the_args)>0 else "a"
            b = the_args[1] if len(the_args)>1 else "b"
            c = the_args[2] if len(the_args)>2 else "c"
            return the_class(self.x, a, b, c)
        if the_class is D:
            return the_class(self.x, the_args[0])

    def do(self):
        for o in self._objs: o.do()


compo = Composite("x", [A, D, A], [(), ("hello",), ("A", "B", "C")])
compo.do()

最佳答案

您可以通过删除类型检查 _make_object 并让类构造函数处理默认参数来缩短它,例如

class Composite(Parent):
    def __init__(self, x, list_of_classes, list_of_args):
        Parent.__init__(self, x)
        self._objs = [
            the_class(self.x, *the_args)
            for the_class, the_args
            in zip(list_of_classes, list_of_args)
            if isinstance(the_class, Parent.__class__)
        ]

    def do(self):
        for o in self._objs: o.do()

这还允许您在不修改其代码的情况下将其用于新类。

关于python - 如何在 python 中以优雅的方式动态创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1367819/

相关文章:

python - 交互式 Matplotlib 窗口未更新

python - Pandas 根据 bool 值创建新列

python - 如何在python中获取一个城市(geonameid)的附近城市?

python - Python 中赋值运算符和复合运算符的区别

python - 求解二次方程

python - 在循环中创建多个数据框

python - cron 没有运行 django 命令

使用 format 命令进行 python 字符串操作

python - PyQt 4 中处理事件的正确方法是什么?

python放入列表