python: inheriting or composition

后端 未结 4 1202
夕颜
夕颜 2021-02-05 13:40

Let\'s say that I have class, that uses some functionality of dict. I used to composite a dict object inside and provide some access from

4条回答
  •  不知归路
    2021-02-05 13:59

    Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go.

    Saving forwarding calls is usually not a good enough reason for choosing inheritance.

    From the Design Pattern book:

    Favor object composition over class inheritance

    Ideally you shouldn't have to create new components to achieve reuse. You should be able to get all the functionality you need by assembling existing components through object composition. But this is rarely the case, because the set of available components is never quite rich enough in practice. Reuse by inheritance makes it easier to make new components that can be composed with old ones. Inheritance and object composition thus work together.

    Nevertheless, our experience is that designers overuse inheritance as a reuse technique and designs are often made more reusable (and simpler) by depending more on object composition."

    The entire text is here: http://blog.platinumsolutions.com/node/129

提交回复
热议问题