继承在这里合适吗?

时间:2018-09-28 19:15:31

标签: python python-3.x oop inheritance

我有一类创建一个对象(一个盒子),并包含重新排列其内容的策略。我认为这应该是两个类,但是,由于我通常使用FP,所以我不确定如何使box class与包含重新排列框内容的策略的solver class一起工作。

box可以是solver的子类吗?似乎不正确。如果没有,我如何使两者一起工作?

class Box(object):        
    def __init__(self, contents, size):
         self.contents = contents
         self.size = size

    def fillBox (self, contents):
        pass


class Solver(object):        
    def __init__(self, boxObject, strategy):
        self.box = boxObject
        self.strategy = strategy

        if self.strategy == strategy1:
            self.strategy1()

    def strategy1 (self):
        // execute some algorithm manipulating the contents of the box

1 个答案:

答案 0 :(得分:3)

通常问自己的问题是:“ ____是____吗?”其中第一个空白是建议的子类,第二个空白是建议的超类,在这种情况下,“ BoxSolver吗?”如果答案是否定的(这里似乎是这种情况),则继承是不合适的。使Solver接受Box作为成为实例属性的参数的方法是正确的处理方法。

相关问题