- Lab
- A Cloud Guru
Creating and Using Python Classes
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 course).
Path Info
Table of Contents
-
Challenge
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
-
Challenge
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 theEmployee
instances are being created inusing_classes.py
:~/using_classes.py
from employee import Employee employee_1 = Employee( name="Kevin Bacon", title="Executive Producer", email_address="[email protected]", phone_number="555-867-5309", ) employee_2 = Employee("Bruce Wayne", "[email protected]", "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 whenemployee_1
is instantiated. Thephone_number
attribute is optional since it isn't used to createemployee_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'
-
Challenge
Implement the `Employee.email_signature` Method
The last few expressions in the
using_classes.py
file demonstrate how theemail_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 ifinclude_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 ifinclude_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
andself.phone_number
are both true, we're able to determine if we should add the phone number to the signature. Let's runusing_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
- By default, the
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.