In this lab, we'll work through creating a class for an 'Employee' from scratch. You will then take these skills to begin creating the 'Contacts' program.
Open Project 9 - Contacts (OOP) through Codespaces or GitHib Desktop / VS Code
Recall that a class is essentially a blueprint (or template) for creating objects.
A class is defined using the class keyword followed by the class name and a colon.
class Employee:
# code goes here
The __init__() method initializes a newly created object. It is called each time a new instance of the defined class is created.
A default parameter, named self is always passed in its argument. This self represents the object of the class itself.
class Employee:
def __init__(self):
# code goes here
Attributes are variables that hold data about an object.
In the Employee class, name and id_number are attributes that store information about an employee.
class Employee:
def __init__(self, name, id_number):
self.name = name
self.id_number = id_number
Notice these are passed to the __init__ method along with self.
It's essential to understand not only how to write classes but also how to visualise their structure. One effective tool for this is the UML (Unified Modeling Language) class diagram. UML class diagrams help us depict the attributes and methods of a class in a clear and standardised way.
The box is divided into three rows: Name, Attributes and Methods
The data type for each attribute is also optionally listed beside it
The return type and parameters of each method is also optionally listed
In this example we have our four parameters in the second row, and the third row is our __init__ method. We will learn more about methods later.
Creating an "instance of the class" means making an actual object from this blueprint.
The Employee class requires two parameters (other than self) be passed in.
Class attributes are variables that are defined directly inside a class but outside any methods. Unlike instance attributes, which are specific to each object created from the class, class attributes are shared across all instances of the class.
This means that if you change a class attribute value, it updates for all instances of that class. They can be used to store constants or data that is common to all objects of the class.
Open lab2.py
Create a class named Contact that represents a contact in a contact management system.
This class should have an initializer with attributes for name, phone_number, and email.
Think of at least one appropriate class attribute to include.
Create at least two instances of the Contact class with different data.
Write code that prints out the details of each contact you have created.
Commit and push your code