What Are Inheritance and Composition?
00:00 Inheritance and composition are two different techniques we can use to write better programs. They both involve modifying classes so that we can not only write less Python code but also write code that is extensible.
00:16 This means that if requirements change or we want to add new features later on, we can do that without rewriting half of the codebase. Informally, this is a part of software architecture: how different pieces of our software—in this case, classes—interact and rely on one another.
00:48 Inheritance is all about identifying the common attributes and behaviors that exist among real-world objects. In the case of Python code, we try to determine how one class might share most or all of the same code as a different class, including the attributes and methods.
Composition is all about identifying how objects are composed of one another. In Python code, you’ve seen how you can create classes with attributes of a specific type, such as
str (string). With composition, these attribute types can move beyond the primitives.
We can have them be a custom type we create by defining a new class. Remember, the type of some object is the class it was instantiated from. That means that if we create a
Person class and we make one of his class attributes a hat, we can make a
Person object have an attribute of type
Hat is a completely separate type we define with its own attributes and methods.