Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

What Are Inheritance and Composition?

Give Feedback

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:37 You’ll learn a lot more about each of these concepts as you progress through the course, but just to give you a primer, here are the big questions that each concept tries to answer.

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.

01:09 The code for our new class might have to be modified a little bit, but that’s okay.

01:15 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 int or str (string). With composition, these attribute types can move beyond the primitives.

01:35 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, where Hat is a completely separate type we define with its own attributes and methods.

02:06 Those are the big ideas behind inheritance and composition. Now, let’s dig a little bit deeper into inheritance.

Become a Member to join the conversation.