Python 复合模式反向顺序函数调用
我有这样的复合类。我想以相反的顺序调用组件函数。我的意思是首先调用最深的子函数,然后再调用一级以上的子函数,依此类推 在下面的示例中,我根据复合对象的子对象计算其权重。因此,首先计算子对象的权重,然后根据子对象的权重计算父对象的权重 我该怎么做?我应该使用什么样的模式或算法Python 复合模式反向顺序函数调用,python,inheritance,composite,Python,Inheritance,Composite,我有这样的复合类。我想以相反的顺序调用组件函数。我的意思是首先调用最深的子函数,然后再调用一级以上的子函数,依此类推 在下面的示例中,我根据复合对象的子对象计算其权重。因此,首先计算子对象的权重,然后根据子对象的权重计算父对象的权重 我该怎么做?我应该使用什么样的模式或算法 class Component(object): def __init__(self,desc,weight, *args, **kw): self.parent = None se
class Component(object):
def __init__(self,desc,weight, *args, **kw):
self.parent = None
self.desc = desc
self.weight_user_defined = weight
def component_function(self):
pass
def setParent(self,parent):
self.parent=parent
class Leaf(Component):
def __init__(self,desc,weight,*args, **kw):
Component.__init__(self,desc,weight, *args, **kw)
def component_function(self):
print (self.desc,self.weight_user_defined)
class Composite(Component):
def __init__(self,desc,weight, *args, **kw):
Component.__init__(self,desc,weight,*args, **kw)
self.children = []
self.weight_calculated = 0.0
def append_child(self, child):
self.children.append(child)
child.setParent(self)
def remove_child(self, child):
self.children.remove(child)
def component_function(self):
print (self.desc,self.weight_user_defined)
for foo in self.children:
foo.component_function()
例如:
ROOT (X kg)
GLOCARY (Y kg)
Apple 2.1 kg
Banana 3.2 kg
MISC (Z kg)
Stuff1 3.3 kg
Stuff2 0.7 kg
因此为了求X,首先计算Y和Z。(或者可能是叶子,例如数量*物品价格)注意:我不确定你所说的“反向顺序函数调用”是什么意思,但这是基于子项计算复合材料重量的方法
没有孩子的
组合
将始终具有weight=0
。我不认为一个组合体有重量是有意义的=0
当它没有子项时
添加孩子时,将孩子的体重添加到组合的体重中。移除儿童时,减去其重量
class Component(object):
def __init__(self,desc,weight=0,*args,**kw):
self.parent = None
self.desc = desc
self.weight = weight
def setParent(self,parent):
self.parent=parent
def getWeight(self):
raise NotImplementedError("Must instantiate subclass")
class Leaf(Component):
def getWeight(self):
return self.weight
class Composite(Component):
def __init__(self,desc, *args, **kw):
super(Composite,self).__init__(desc,*args, **kw)
self.children = []
def append_child(self, child):
self.children.append(child)
child.setParent(self)
self.weight += child.getWeight()
def remove_child(self, child):
self.children.remove(child)
self.weight -= child.getWeight()
def getWeight(self):
return self.weight
在这里,我通过添加Leaf
s和Composite
s作为另一个Composite
的子项进行演示
c1 = Composite("Composite 1")
c2 = Composite("Composite 2")
c1.append_child(Leaf("A leaf",5))
c1.append_child(Leaf("A leaf",5))
c1.append_child(Leaf("A leaf",5))
c2.append_child(Leaf("A leaf",1))
c2.append_child(Leaf("A leaf",1))
c2.append_child(Leaf("A leaf",1))
c1.append_child(c2)
输出
我看不出你在计算什么。您只需打印复合材质及其所有子对象的权重。我猜通过计算,你的意思是你想把孩子们的体重累加起来?是的,菲利普,你是对的。我想把重量累加起来。我想执行求和,而不是打印。我明白了。您提到要先在最深的子级中调用函数?为什么会这样,如果我们只给父母打电话,然后递归地打电话,直到我们碰到最深的孩子,这对我来说是有意义的。嗨,菲利普,我编辑了这个问题。这也是一个解决方案,但我正在寻找这样的解决方案;在增加或减少项目时,不应增加或减少总数。相反,在添加项目后,我想调用update()或calculate()函数,该函数从下到上累加项目和中间父项。
In [2]: print(c1.getWeight())
18
In [3]: c1.remove_child(c2)
...: print(c1.getWeight())
...:
15