Sunday, February 9, 2014

Inheritance, Multiple Inheritance, and Composition

Inheritance is one of the most important features offered by Object-Oriented Programming languages.  We can create a subclass of a base class by passing the base class name as an argument in the subclass class definition (only if the base class is available in the current module, of course!). By proceeding this way, the subclass “inherits” all the attributes and methods of the base class. 

For example, let’s say that we create a class called Car. In the __init__ method of Car we will define some default attributed such as wheels, windows…and we will also include some methods in the implementation of this class such as accelerating or breaking…
Later on, we can create a subclass of Car called Ferrari, that will inherit all the properties of Car. This allows us to add attributes and methods to Ferrari without modifying Car and it will also save us tons of lines of code if we were going to create a Ferrari class from scratch!

Inheritance is in fact a very powerful and useful tool, but we need to know when to avoid it…
Multiple inheritance is usually something that should be avoided. This takes place when we create a subclass of two or more base classes. Multiple inheritance makes our code too complex and it can get confusing to choose names for new methods in our subclass if similar methods with similar names are defined in our base classes.

This is why we should always consider composition. We can call baseclass.__init__(self) inside the implementation of our subclass __init__ method to tell Python that we want our subclass to have the same attributes as our base class but the methods of base class will not be inherited by the subclass. Furthermore, we can call any method of the base class inside the implementation of the subclass by calling baseclass.method(self)

No comments:

Post a Comment