Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences 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 refer to our video player troubleshooting guide for assistance.

Introduction to OOP Inheritance

In this video, you’ll learn how inheritance is used to write maintainable Python code that avoids redundancy.

Inheritance allows one class to subclass another. If we want to make the Baby class a child class of the Person class, we can define Baby like this:

Python
class Baby(Person):
    # Baby code here

By default, any Baby object we create will inherit its attributes and methods from its parent. This means it will have the same attributes and members that the parent class defined.

In the video, you’ll see how you can override a method so that the Baby class can contain a different implementation for that method. You’ll also learn how to extend the functionality of the Baby class by defining new methods, which will be exclusive to only Baby objects.

The isinstance() function is used to determine if an object is of a specific type. It takes 2 arguments: the object to be checked, and a type to check against. It supports inheritance, so in the example of our Baby and Person objects, isinstance(baby, Person) will return True because our Baby class is the child class of Person, and so we can say our baby object is a Person too.

00:00 Welcome back to our series on object-oriented programming in Python. In the last video, we learned about instance methods, which are used to represent the behaviors our objects have. This whole idea of classes, creating objects—little bundles of associated data and actions—is a really powerful thing, but it’s also susceptible to a bad coding practice called DRY. DRY stands for Don’t Repeat Yourself. This says that when we write code, we should avoid copying and pasting the same chunks of code whenever possible.

00:33 If you’re writing a nontrivial Python program and you find yourself copying and pasting attributes and instance methods between a lot of different classes, that means that it’s probably time to rethink how you’re designing your software. Take a look at this example.

00:48 Let’s say we are writing a program that’s supposed to construct and maintain lots of different people. As you can probably guess, each person is going to be an object—but here’s the caveat: we can have general people objects, and then we can have a special type of person called a baby.

01:06 A baby can do everything a regular person can do, except it might do some things a little bit differently, like talking. In addition, it might also have some unique behaviors that our general person doesn’t have, such as the ability to take a nap whenever it wants. Being a baby sounds great.

01:25 As you might have guessed, we’re going to need two different classes here: one for the person, and then one for the baby. You’ll notice here that both of these classes are the exact same, but the Baby class has one more behavior called .nap().

01:40 Now, we could design our software this way and it would work fine, but remember, a baby has to be able to do everything a more general person can do, albeit a little bit differently sometimes. This means that our Baby class is going to have the same instance methods that the Person class has, and most of those methods are going to look the exact same,

02:01 But now, what happens if we want to make a change to the Person class? If we change the .action()` method from something like jumping to spinning, then we also have to change the baby’s .action() method as well.

02:16 And if we add other classes, like Adult or Teenager, then we’d also have to maintain those, too. Copying code might make things easier in the moment, but it can make our software really difficult to maintain later on, especially as it grows. To solve this problem, let’s take a step back and think about the relationships that exist between these two classes.

02:37 I think that you would agree that a baby is a person, right? That’s why it shares the same behaviors as the Person class. So, what if there was a way that we can make the Baby class automatically inherit every attribute and instance method from the Person, but then modify them a little bit to fit the Baby class’ needs.

02:58 Then, we could even add our own behavior, like .nap(), that would be exclusive to the Baby class. This right here is called object inheritance, and if used right, it makes managing lots of similar classes a lot easier.

03:14 Inheritance allows us to make one class the child class, or the derived class, of another class called the parent class, or the base class. In Python, the child class automatically inherits every attribute and instance method from the parent class, but we can also redefine certain attributes or methods.

03:35 So, if we want our Baby object to speak differently than a Person object would, we can do that. If we want our Baby object to have the ability to nap, we can do that too. And if we need to make our person spin, instead of jump, we can modify the Person class and the Baby class will automatically pick up those changes.

03:55 There’s no need to edit code in more than one place. To understand inheritance, take a look at this chart on the right. At the very top of the chart is object. In

04:06 many languages, Python included, object is the parent class of all classes in the language. This includes built-in classes, like the int or the str, as well as any custom classes we create. In this diagram, you can see that Baby inherits from Person, which in turn inherits from object.

04:26 As we’ll see later on, Python sees any Baby object we create as also a Person and an object.

Peter T on March 22, 2019

In the above text, please change exampole to example.

John T on March 28, 2019

Lovely tutorial. very clear and concise. but dawg , its 2019. use f strings :)

Eriberto on April 27, 2019

f string +1 lol why can’t we streamline the use of awesome formatting method python 2 is dead soon 😀

justpeter25x on Nov. 15, 2019

Thank you.The course is very good . If you provide the video transcript with the course it will be very helpful.It will save our time

Austin Cepalia RP Team on Nov. 16, 2019

@justpeter25x That’s a good idea, but unfortunately that’s beyond my control

Dan Bader RP Team on Nov. 16, 2019

Thanks for your comment @justpeter25x. I’m planning to bring full transcripts and subtitles to all courses on Real Python in the future. It’s a huge project but I agree that it will be very useful. Stay tuned :)

L3ARaX on Dec. 25, 2019

Can’t wait for an English subtitles for non native speakers… like me ^_^.

mathewschristopher on Aug. 17, 2023

class C:
    attribute1 = ''  # This is called as a class attribute

    def meth(self, attribute2):  # This is an instance method
        self.attribute2 = attribute2 
        # Here attribute2 is an instance attribute

    def func():  # What do we call this function inside a class which exists for all the objects or is it called a class method like how we say class attribute?
        pass 

Bartosz Zaczyński RP Team on Aug. 18, 2023

@mathewschristopher All functions defined inside a class are known as methods. Python has three kinds of methods:

  • instance methods
  • class methods
  • static methods

You can learn more about their differences by reading a tutorial devoted to those methods: Python’s Instance, Class, and Static Methods Demystified.

Note that your code is syntactically incorrect. In order to define a static method, i.e., one which doesn’t take the self parameter, you need to explicitly annotate it with the @staticmethod decorator:

class C:
    @staticmethod
    def do_something():
        pass

Andras on April 22, 2024

Very good intro tutorial, thank you. Just one comment though: in the (UML) class diagrams the arrows should be pointing from the subclass to the parent class.

Become a Member to join the conversation.