Creating and Using Python Classes

45 minutes
  • 3 Learning Objectives

About this Hands-on Lab

As we work on more and more complex problems, we need to start creating custom types to have manageable models for the data we’re working with. Python is an object-oriented programming language, and creating classes is something we will do frequently to solve problems using Python. In this hands-on lab, we’ll define a custom class with some functionality and attributes that will allow us to model an `Employee` in our code. The `using_classes.py` script includes code that will utilize this class and provide us with some feedback to know if we’ve created a class that meets our requirements. 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).

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create the `employee` Module with an Empty `Employee` Class

Before we write any code, let’s see what we need to do to get the using_classes.py file to execute to the next step by looking at the error:

$ python3.7 using_classes.py
Traceback (most recent call last):
  File "using_classes.py", line 1, in <module>
    from employee import Employee
ModuleNotFoundError: No module named 'employee'

This error shows us the first thing we need to do is create the module and the Employee class within it. The error doesn’t tell us anything else, though, so we’ll take the smallest step possible to move to the next step. Let’s create an empty class now:

~/employee.py

class Employee:
    pass

Running using_classes.py again, we’ll see a new error:

$ python3.7 using_classes.py
Traceback (most recent call last):
  File "using_classes.py", line 7, in <module>
    phone_number="555-867-5309",
TypeError: Employee() takes no arguments
Implement the `Employee.__init__` Method

Our next error is related to not having an __init__ method that takes arguments. To know what we need to implement, let’s look at how the Employee instances are being created in using_classes.py:

~/using_classes.py

from employee import Employee

employee_1 = Employee(
    name="Kevin Bacon",
    title="Executive Producer",
    email_address="kbacon@example.com",
    phone_number="555-867-5309",
)
employee_2 = Employee("Bruce Wayne", "bwayne@example.com", "CEO")

# Rest of code omitted

We can see here the positional order for our arguments is given from the employee_2 line, and the name of the attributes are provided by the keyword argument usage when employee_1 is instantiated. The phone_number attribute is optional since it isn’t used to create employee_2. Let’s take this knowledge and implement the __init__ method now:

~/employee.py

class Employee:
    def __init__(self, name, email_address, title, phone_number=None):
        self.name = name
        self.email_address = email_address
        self.title = title
        self.phone_number = phone_number

Now we shouldn’t have any issues creating our instances in using_classes.py:

$ python3.7 using_classes.py
Traceback (most recent call last):
  File "using_classes.py", line 12, in <module>
    employee_1.email_signature(include_phone=True)
AttributeError: 'Employee' object has no attribute 'email_signature'
Implement the `Employee.email_signature` Method

The last few expressions in the using_classes.py file demonstrate how the email_signature method should work. The two main things to note are:

  • By default, the phone_number attribute is not included in the string that is returned; but if include_phone is true, then it is added to the end of the second line.
  • If there is no phone_number, then the phone number portion will not be printed, even if include_phone is true.

Let’s implement this method now:

~/employee.py

class Employee:
    def __init__(self, name, email_address, title, phone_number=None):
        self.name = name
        self.email_address = email_address
        self.title = title
        self.phone_number = phone_number

    def email_signature(self, include_phone=False):
        signature = f"{self.name} - {self.title}n{self.email_address}"
        if include_phone and self.phone_number:
            signature += f" ({self.phone_number})"
        return signature

By checking if include_phone and self.phone_number are both true, we’re able to determine if we should add the phone number to the signature. Let’s run using_classes.py one more time to ensure everything works. We should see no output if we’ve implemented the method correctly.

python3.7 using_classes.py

Additional Resources

We're in the process of building a larger system that can work with internal employee information. To begin, we want to create a simple version of the Employee class that can hold on to an employee's name, title, email address, and phone number. Specifically, we want the class to have these attributes:

  • name: String, required
  • title: String, required
  • email_address: String, required
  • phone_number: String, optional

For the time being, we would like to have an instance of Employee generate an email signature that the employee could use.

  • email_signature: Returns multi-line string with email signature. If this method receives include_phone with a true value, then it should include the employee's phone number; otherwise, it should be left off.

Another engineer on the team wrote a script that demonstrates how the class could be used, and it will provide us with a means to check our implementation. We will run using_classes.py as we're creating the Employee class in the employee.py module.

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, 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.

Get Started
Who’s going to be learning?

How many seats do you need?

  • $499 USD per seat per year
  • Billed Annually
  • Renews in 12 months

Ready to accelerate learning?

For over 25 licenses, a member of our sales team will walk you through a custom tailored solution for your business.


$2,495.00

Checkout
Sign In
Welcome Back!

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