Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: inheriting or composition

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 the outside, but recently thought about simply inheriting dict and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to composition?

like image 703
gruszczy Avatar asked Mar 05 '10 20:03

gruszczy


People also ask

Is inheritance better than composition?

One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don't know what all methods of superclass will be used.

What is the difference between composition and inheritance in Python?

For example, your Horse class can be composed by another object of type Tail . Composition allows you to express that relationship by saying a Horse has a Tail . Composition enables you to reuse code by adding objects to other objects, as opposed to inheriting the interface and implementation of other classes.

Is composition the same as inheritance?

Composition is in contrast to inheritance, it enables the creation of complex types by combining objects (components) of other types, rather than inheriting from a base or parent class. To put it simply, composition contains instances of other classes that implement the desired functionality.

When should use inheritance when should we use composition?

Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition defines a class as the sum of its parts.


1 Answers

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

like image 86
Philippe Beaudoin Avatar answered Sep 19 '22 13:09

Philippe Beaudoin