2_Classes
2_Classes
2.2. Classes
• What are classes?
• Creating and using a class
• Working with Classes and Instances
• Inheritance
• Importing Classes
What are classes? 3
9-1,…,9-3
Practice 8
Exercise: Email Class with Methods
Create an Email class with the following attributes: email_address
(the email address of the user), inbox (a list to store received emails),
and sent (a list to store sent emails). Implement the following methods
for the class:
1. Method __init__(self, email_address): Initialize an Email object with
the given email_address. Initialize inbox and sent lists as empty
lists.
2. Method send(self, recipient, message): Create an email with the
given message and send it to the specified recipient. Add the sent
email to the sent list of the sender and add the email to the
recipient's inbox.
3. Method read(self): Print all the emails in the inbox.
4. Method delete(self, index): Delete the email at the specified index
from the inbox.
Here's a sample template to help you get 9
started:
Working with Classes and Instances 10
Reference: https://www.pythonlikeyoumeanit.com/Module4_OOP/Special_Methods.html
Special Methods 15
String-Representations of Objects
Method Signature Explanation
repr(x) invokes x.__repr__(), this
Returns string for a printable
__repr__(self) is also invoked when an object is
representation of object
returned by a console
Returns string
__str__(self) str(x) invokes x.__str__()
representation of an object
Special Methods 16
1. Class Variables:
• Scope: Class variables are shared among all objects of a class.
• Declaration and Usage: Declared inside the class and can be accessed
without creating an object.
• Access: Can be accessed through the class name without creating an
object.
Class Variables vs. Object Variables 21
2. Object Variables:
• Scope: Object variables belong to a specific instance of a class.
• Declaration and Usage: Declared and used through an object created
from the class.
• Access: Requires creating an object of the class to access the object
variable.
Class Variables vs. Object Variables 23
Purpose:
• Organize code: Improve code
organization by encapsulating
related classes.
• Encapsulation: Hide inner class
details from the outer world,
enhancing data security.
Nested Classes 26
Calling Methods:
Nested Classes 27
• You don’t always have to start from scratch when writing a class. If the
class you’re writing is a specialized version of another class you wrote,
you can use inheritance.
• When one class inherits from another, it takes on the attributes and
methods of the first class.
• The original class is called the parent class, and the new class is the
child class.
• The child class can inherit any or all of the attributes and methods of its
parent class, but it’s also free to define new attributes and methods of
its own.
Inheritance 29
Instances as Attributes
Practice 33
9-6,…,9-9
Importing Classes 34
Using Aliases