In this lab, we'll continue working through creating a class for the 'Employee'. This time we will add functionality by adding "Methods".
Open Project 9 - Contacts (OOP) through Codespaces or GitHib Desktop / VS Code
In object-oriented programming, methods are like functions that belong to a class. They define how we can interact with an object created from that class or the class itself. There are two main types of methods we'll focus on: instance methods and class methods.
Instance methods are actions that objects created from a class can perform.
They work on the data contained within an object (instance) and can access and modify the state of that object using self.
Notice we don't have to supply self as an argument to get_full_name() when it is called on the employee1 object.
We do, however, need to use self when referring to the attributes in the method definition.
Class methods work on the class itself rather than the instance. They can't access specific instance data but can access class attributes.
To define a class method, we use the @classmethod decorator. This decorator tells Python that the method below it is not meant to be used with instances, but with the class itself. The decorator transforms a method into a "class method" that, instead of accepting self (which represents an instance) as the first argument, accepts cls (which represents the class).
Class methods are often used for modifying values that apply to all instances, or for utility functions that perform tasks not tied to individual objects.
Here we will continue to build on our understanding of UML class diagrams by adding in our methods:
In this example we have:
Underlined our class attributes and methods, and included them before our instance attributes and methods
Included any parameters and their data types within parenthesis
Included any return type after a colon
Open lab3.py
Complete the following activities:
Copy/paste your Contact class from Lab 2.
Add a check_email method to check if the email contains an '@'
Create a class method get_contact_count to retrieve the number of contacts
Reproduce the instances of the Contact class that you created in Lab 2
Call your new instance method on one Contact and print the result
Use the class method to print out the total number of contacts
Commit and push your code