Author - StudySection Post Views - 1,307 views
Class Composition

Class Composition in Python

Introduction to Class composition

Class composition is an alternative to class inheritance. It is much more useful than the latter. It reduces the complexity of code and makes it much easier to understand. Consider this code :

code01

Analyzing the approach

This makes little sense as we can see, in this code, class ‘Book’ inherits from the class ‘Bookshelf’. The idea being, a book is contained inside the bookshelf. Here we need to use the__str__ method inside the Book class in order to avoid printing “Bookshelf with 150 books” and print “Book 5 Second Rule” when printing an object of Book class. While this may work, its a bad approach and this is for two reasons:-

  1. Conceptual issue – The conceptual reason is that when we do inheritance, we are essentially treating it as an evolutionary inheritance. We’re saying that a book is a bookshelf and something more. For example, akin to the fact that all tigers are mammals, but not all mammals are tigers. So all books are bookshelves, but not all bookshelves are books. The bookshelf can still be used on its own. That breaks down when we talk about books and bookshelves because a book is something completely different from a bookshelf. A bookshelf can contain books, but one isn’t the other.
  2. Technical issue – The technical reason why this breaks down is that we’ve got this book class that inherits from the bookshelf, but actually we are not using inside it anything about the bookshelf. So we are completely overriding the __str__ method because we don’t want anything to do with bookshelves in there. We actually don’t need these at all because there is no point in setting the quantity if we’re not going to use it in the methods.

So the conceptual reason is that a book is not a bookshelf and the technical reason is that there is no reason to inherit if we don’t use the inheritance anywhere. So this is where the composition comes in.
Instead of setting the number of books in the bookshelf, we can allow the constructor to take in a number of books.

code02

code03

Here, we have removed the super method and the quantity parameter. Updated the __str__ method in the Bookshelf class to find the length of the books tuple(*self.books) which can contain N number of books. It is used for passing an arbitrary number of arguments. We create an object of Bookshelf class called ‘shelf’, pass in the books and print it which will return the __str__ method in the bookshelf class. As you can see our code has become much simpler, cleaner and it allows us to add several books to the bookshelf.

Get certification for your knowledge in the fundamentals of Computer functioning by clearing the Computer Certification exam conducted by StudySection. After going through this Computer Certification exam, you will be able to evaluate your basic knowledge of computers.

Leave a Reply

Your email address will not be published.