Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.
  • Labs icon Lab
  • A Cloud Guru
Google Cloud Platform icon
Labs

Using Inheritance in Python

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 course) and use inheritance and `super` (watch the "Inheritance and Super" video from the Certified Associate in Python Programming Certification course).

Google Cloud Platform icon
Labs

Path Info

Level
Clock icon Intermediate
Duration
Clock icon 45m
Published
Clock icon Mar 20, 2020

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    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'
    
  2. Challenge

    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'
    
  3. Challenge

    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'
    
  4. Challenge

    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
    

The Cloud Content team comprises subject matter experts hyper focused on services offered by the leading cloud vendors (AWS, GCP, and Azure), as well as cloud-related technologies such as Linux and DevOps. The team is thrilled to share their knowledge to help you build modern tech solutions from the ground up, secure and optimize your environments, and so much more!

What's a lab?

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.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.

Start learning by doing today

View Plans