The world’s leading publication for data science, AI, and ML professionals.

Mastering Class Inheritance in Python

Understanding Class Inheritance in Python

Photo by Max Fischer on Pexels
Photo by Max Fischer on Pexels

Inheritance is a concept in object oriented Programming where existing classes can be modified by a new class. The existing class is called the base class and the new class is called the derived class. In this post, we will discuss class inheritance in python.

Let’s get started!

The syntax of Python class inheritance is as follows:

class BaseClass: 
    #body of BaseClass
class DerivedClass(BaseClass): 
    #body of DerivedClass

For our example we will consider a SpotifyUser derived class inheriting from FacebookUser base class. First let’s define our FacebookUser class:

class FacebookUser: 
    pass

Now let’s consider some attributes of a Facebook user. Let’s add a first name, last name and a list of friends:

class FacebookUser:
    def __init__(self, first_name, last_name, friends_list): 
        self.first_name = first_name
        self.last_name = last_name
        self.friends_list = friends_list

We can also add a method that prints the full name of a user:

class FacebookUser:
    ...
    def print_name(self):
       print(f'{self.first_name} {self.last_name}')

Let’s also add a method that prints the list of friends:

class FacebookUser: 
    ...
    def print_friends(self):
       print(f'{self.friends_list}')

Now let’s create an instance of the FacebookUser class:

User1 = FacebookUser('Mike', 'Tyson', ['Buster Douglas', 'Evander Holyfied', 'Roy Jones Jr.'])

Now we can call the ‘print_name’ method:

User1.print_name()

Next let’s call the ‘print_friends’ method:

User1.print_friends()

Now let’s create a SpotifyUser class that will inherit the methods and attributes from the FacebookUser class:

class SpotifyUser(FacebookUser):
    pass

When we add an ‘init‘ method to the derived class it overrides the base class ‘init‘ method. In the ‘init‘ method of the derived class we can use the ‘super()’ function to make the SpotifyUser class (derived) inherit all of the methods and attributes from the FacebookUser class (base):

class SpotifyUser(FacebookUser):
    def __init__(self, first_name, last_name, friends_list):
        super().__init__(first_name, last_name, friends_list)

Typically we override the definition of the base class ‘init‘ method to extend the definition. Let’s extend the definition by adding a playlist attribute:

class SpotifyUser(FacebookUser):
    def __init__(self, first_name, last_name, friends_list, playlist):
        super().__init__(first_name, last_name, friends_list)
        self.playlist = playlist

Now let’s create an instance of our SpotifyUser class:

user2 = SpotifyUser("Floyd", "Mayweather", ['Buster Douglas', 'Evander Holyfied', 'Roy Jones Jr.'], ["Harry Styles", "Taylor Swift"])

Now, we can use the ‘print_name’ method from our base class on our derived class:

user2.print_name()

And we can also call the ‘print_friends’ method on our derived class instance:

user2.print_name()

Finally we can add a method to our child class. Let’s add a method that prints the Spotify user’s playlist:

class SpotifyUser(FacebookUser):
    ...
    def get_playlist(self):
        print(f"{self.first_name} {self.last_name}'s playlist: {self.playlist}")
User2.get_playlist()

I’ll stop here but feel free to play around with the code yourself.

CONCLUSIONS

To summarize, in this post we discussed how to implement a base and derived class in python, where the derived class inherits methods and attributes from the base class. First, we defined our base class as a FacebookUser class. We then defined a derived class called SpotifyUsers which inherited methods and attributes from the FacebookUser class. If you are interested learning about the basics of python programming, data manipulation with Pandas, and machine learning in python check out _Python for Data Science and Machine Learning: Python Programming, Pandas and Scikit-learn Tutorials for Beginners._ I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!


Related Articles