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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值