发布于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黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!