程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2020-02-16 18:45     阅读(1300)     评论(0)     点赞(28)     收藏(2)


我有两个要合并为一个复合的类。这两个类将继续独立使用,我不想修改它们。由于某些原因,我想让我的复合类创建对象。我正在考虑类似下面的代码(仅作为示例),但是我认为它很复杂,我不太喜欢。我想可以通过一些我忽略的技术和技巧来改善它。

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

有什么建议可以改善此代码?

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()

解决方案


您可以通过删除type-checking来缩短它_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()

这也将允许您将其与新类一起使用,而无需修改其代码。



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/231613/5a4d60b6a12481665934/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)