Using Inheritance in Python

45 minutes
  • 4 Learning Objectives

About this Hands-on Lab

Modeling problems using objects is incredibly powerful, and having more specific classifications can make modeling complex problems even easier. Inheritance allows us to do this with our classes. In this hands-on lab, we’ll expand the classifications we have for employees in our codebase by adding a subclass with more functionality. To feel comfortable completing this lab, you’ll want to know how to create and use Python classes (watch the “Creating and Using Python Classes” video from the [Certified Associate in Python Programming Certification](https://linuxacademy.com/cp/modules/view/id/470) course) and use inheritance and `super` (watch the “Inheritance and Super” video from the [Certified Associate in Python Programming Certification](https://linuxacademy.com/cp/modules/view/id/470) course).

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create the `Manager` Class in a New `manager` Module

The first thing we need to do is create our class and have it inherit from the Employee class. This will move our script forward. Let’s create the manager.py file and create the Manager class.

~/manager.py

from employee import Employee

class Manager(Employee):
    pass

Now if we run the using_inheritance.py script, we should see the following error:

$ python3.7 using_inheritance.py
Traceback (most recent call last):
  File "using_inheritance.py", line 23, in <module>
    manager_1.meetings == []
AttributeError: 'Manager' object has no attribute 'meetings'
Add a New `meetings` Attribute That Defaults to an Empty List

The error we’re running into shows we don’t have a meetings attribute, and since we want to default this to an empty list, we’ll need to customize the __init__ method for our class. The method signature needs to be exactly like Employee, so we’ll copy that over, but then we’ll need to utilize super before finally adding our new attribute.

~/manager.py

from employee import Employee

class Manager(Employee):
    def __init__(self, name, email_address, title, phone_number=None):
        super().__init__(name, email_address, title, phone_number)
        self.meetings = []

This should be enough to move us to the next error:

$ python3.7 using_inheritance.py
Traceback (most recent call last):
  File "using_inheritance.py", line 32, in <module>
    manager_1.schedule_meeting(invitees, meeting_time1)
AttributeError: 'Manager' object has no attribute 'schedule_meeting'
Add a `schedule_meeting` Method to the `Manager` Class

The schedule_meeting method needs to take an invitees list and a time that will be a datetime object. We will use this information to build a simple dictionary, add it to meetings, and then sort meetings by the time attribute. Let’s implement this method now:

~/manager.py

from employee import Employee

class Manager(Employee):
    def __init__(self, name, email_address, title, phone_number=None):
        super().__init__(name, email_address, title, phone_number)
        self.meetings = []

    def schedule_meeting(self, invitees, time):
        self.meetings.append({"invitees": invitees, "time": time})
        self.meetings.sort(key=lambda m: m["time"])

Here’s the next error we will see with this method implemented:

$ python3.7 using_inheritance.py
Traceback (most recent call last):
  File "using_inheritance.py", line 42, in <module>
    result = manager_1.run_next_meeting()
AttributeError: 'Manager' object has no attribute 'run_next_meeting'
Add a `run_next_meeting` Method to the `Manager` Class

The last method we need to implement is the run_next_meeting method that will remove and return the first meeting dictionary in the meetings list. Thankfully, this can easily be done by using the list.pop method with the argument of 0:

~/manager.py

from employee import Employee

class Manager(Employee):
    def __init__(self, name, email_address, title, phone_number=None):
        super().__init__(name, email_address, title, phone_number)
        self.meetings = []

    def schedule_meeting(self, invitees, time):
        self.meetings.append({"invitees": invitees, "time": time})
        self.meetings.sort(key=lambda m: m["time"])

    def run_next_meeting(self):
        return self.meetings.pop(0)

With this implementation, we should have fully implemented everything required for the using_inheritance.py script to successfully execute.

$ python3.7 using_inheritance.py

Additional Resources

We're building up the classes for an application that will manage employees in our organization, and we'd like to add more functionality to employees who are managers that will allow them to schedule and run meetings. To achieve this, we'll add an additional class called Manager that inherits from our Employee class. A meeting in our system will be a dictionary that includes the following keys:

  • invitees: A list of Employee objects representing who is invited to the meeting
  • time: A datetime object that represents when the meeting will happen

To make it easy to schedule meetings, we will add a schedule_meeting method that takes a list of invitees and a datetime. This meeting will be added to the meetings attribute, and the list will be sorted by the time. Additionally, the run_next_meeting method will remove the first meeting from the list of meetings and return it.

To see if our code is working as expected, we can run the using_inheritance.py file that demonstrates the ideal usage of the new class. If this script runs without error, our code meets the requirements.

Logging In

There are a couple ways to get in and work with the code. One is to use the credentials provided in the hands-on lab overview page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in the browser. If you'd like to go this route, then you will need to navigate to the public IP address of the workstation server (provided in the hands-on lab overview page) on port 8080 (example: http://<PUBLIC_IP>:8080). Your password will be the same password that you'd use to connect over SSH.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?