More often than building your own child classes, you'll build separate custom objects and combine them with one another. This concept is called object composition and there's a popular opinion that when it comes to composition vs inheritance, it's better to use composition over inheritance.
What is Object Composition
The fundamental idea of the composition meaning is that it's often more straightforward to define an object through what it has rather than what it is. You can then build a larger object (composites) from multiple smaller objects (components).
For example, if you wanted to build a Kitchen() class, it can seem more straightforward to define it through other objects it has rather than through inherited properties of a shared parent Room() class:
class Kitchen():
def __init__(Stove, Sink, Fridge, Countertop):
...
With this stub code snippet, you could imagine that your composite Kitchen() class takes smaller component objects (Stove(), Sink(), Fridge(), Countertop()) and composes them to define the functionality and attributes that make up a kitchen.
Before moving on to the next lesson, give it a try to build out the mentioned classes and compose them into a useful Kitchen() class. Post your example code and your thoughts on using composition over in Discord.
When you're done with your own implementation, move on to the next page to see an example of how you might solve this challenge.
Summary: Python Composition Definition
- Object composition is the idea that one object may be "composed" of many others
- Object composition is often preferred over inheritance
- This lesson provides an example of object composition when creating a
Kitchenclass