0% found this document useful (0 votes)
0 views

2_Classes

Chapter 2 covers the fundamentals of functions and classes in Python, emphasizing the importance of classes in object-oriented programming. It explains how to create and use classes, the concept of inheritance, and provides practical exercises for implementing classes such as Email, User, and Rectangle. Additionally, it discusses class variables versus object variables, nested classes, and the process of importing classes in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

2_Classes

Chapter 2 covers the fundamentals of functions and classes in Python, emphasizing the importance of classes in object-oriented programming. It explains how to create and use classes, the concept of inheritance, and provides practical exercises for implementing classes such as Email, User, and Rectangle. Additionally, it discusses class variables versus object variables, nested classes, and the process of importing classes in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter 2: Functions and classes

Lecturer: Nguyen Tuan Long, Phd


Email: [email protected]
Mobile: 0982 746 235
Chapter 2: Functions and classes 2

2.2. Classes
• What are classes?
• Creating and using a class
• Working with Classes and Instances
• Inheritance
• Importing Classes
What are classes? 3

• Classes are the foundation of object-oriented programming.


• Classes represent real-world things you want to model in your programs:
for example: dogs, cars, and robots….
• You use a class to make objects, which are specific instances of dogs, cars,
and robots.
• A class defines the general behavior that a whole category of objects can
have, and the information that can be associated with those objects.
• Classes can inherit from each other – you can write a class that extends
the functionality of an existing class. This allows you to code efficiently for
a wide variety of situations.
Creating and using a class 4

Creating the Dog Class

Name Age Weight

Sit Roll over


Creating and using a class 5

Creating the Dog Class define a class


called Dog
docstri
ng
attribute
s
Method

The __init__() Method


is a special method that Python runs automatically
whenever we create a new instance based on the Dog class
Creating and using a class 6

Making an Instance from a Class

Accessing Calling Creating Multiple


Attributes Methods instances
Practice 7

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

The Car Class


Working with Classes and Instances 11

Setting a Default Value for an Attribute


Working with Classes and Instances 12

Modifying Attribute Values


Modifying an Attribute’s Value Directly

Modifying an Attribute’s Value Through a Method


Working with Classes and Instances 13

Incrementing an Attribute’s Value Through a Method


Special Methods 14

• All the built-in data types implement a collection of special object


methods.
• The names of special methods are always preceded and followed by
double underscores (__).

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

Interfacing with Mathematical Operators


Method Signature Explanation
Add __add__(self, other) x + y invokes x.__add__(y)
Subtract __sub__(self, other) x - y invokes x.__sub__(y)
Multiply __mul__(self, other) x * y invokes x.__mul__(y)
Divide __truediv__(self, other) x / y invokes x.__truediv__(y)
Power __pow__(self, other) x ** y invokes x.__pow__(y)
Special Methods 17

Creating a Container-Like Class

Method Signature Explanation


Length __len__(self) len(x) invokes x.__len__()
Get Item __getitem__(self, key) x[key] invokes x.__getitem__(key)
x[key] = item invokes x.__setitem__(ke
Set Item __setitem__(self, key, item)
y, item)
Contains __contains__(self, item) item in x invokes x.__contains__(item)
Iterator __iter__(self) iter(x) invokes x.__iter__()
Next __next__(self) next(x) invokes x.__next__()
Practices 18

Exercise: Custom String Representation


Create a User class representing a user with attributes
username and email. Implement the following special
methods:
1. __init__(self, username, email): Initialize the user
object with the given username and email.
2. __str__(self): Return a string representation of the user
in the format "User: username, Email: email".
Practices 19
Exercise : Rectangle Class
Create a Rectangle class representing a rectangle with attributes width
and height. Implement the following special methods:
1. __init__(self, width, height): Initialize the rectangle object with the
given width and height.
2. __str__(self): Return a string representation of the rectangle in the
format "Rectangle(width, height)".
3. __eq__(self, other): Compare two rectangles based on their area.
Return True if the areas of the two rectangles are equal, otherwise
False.
4. __lt__(self, other): Compare two rectangles based on their area.
Return True if the area of the current rectangle is less than the area
of the other rectangle, otherwise False.
5. __add__(self, other): Calculate the total area of two rectangles and
return a new rectangle with a width equal to the sum of the widths of
the two rectangles and a height equal to the sum of the heights of the
Class Variables vs. Object Variables 20

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

Exercise 1: Class Variable


1. Create a class BankAccount with a class variable
interest_rate to store the common interest rate for all
bank accounts.
2. Write a class method set_interest_rate(rate) to set a
new interest rate for all bank accounts.
3. Create two objects account1 and account2 from the
BankAccount class.
4. Modify the interest rate through the class variable and
check if both accounts share the new interest rate.
Class Variables vs. Object Variables 22

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

Exercise 2: Object Variables


1. Create a class Book with object variables title to store
the book's title and author to store the author's name.
2. Create two objects book1 and book2 from the Book
class with appropriate values for title and author.
3. Write a class method display_info() to display
information about the book, including both title and
author.
4. Call the display_info() method on both book1 and
book2 objects to display the book information.
Class Variables vs. Object Variables 24

Exercise 3: Combination of Class and Object Variables


1. Extend the Book class from Exercise 2 to include a class
variable total_books to track the total number of books
created.
2. Create a class method display_total_books() to display
the total number of books created.
3. Whenever a new Book object is created, increase the
value of total_books by 1 using the class variable.
4. Create a book3 object from the Book class and call the
display_total_books() method to show the total number
of books created.
Nested Classes 25

Definition: Syntax of Nested


• Nested classes, also known as Classes
inner classes, are classes defined
within another class in Python.

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

Working with Nested Classes


Creating Objects:

Calling Methods:
Nested Classes 27

Exercise: Creating a Classroom System with Nested Classes


Imagine you are building a simple classroom system in Python. Design a class
structure using nested classes to represent the following entities: Classroom and
Student.
Classroom Class:
•Attributes:
•class_name: Name or identifier of the classroom.
•Nested Class: Student
•Attributes:
•name: Name of the student.
•roll_number: Unique identifier for the student.
•Methods:
•display_info(): Display student information including name and roll
number.
Inheritance 28

• 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

The __init__() Method for a Child Class

Name of parent class


define the child
takes class
in the information required to make a Car
instance

tells Python to call the


special function that allows you to call a method from the __init__()
parent class method from Car, which
gives an ElectricCar instance
all the attributes defined in
that method.
Inheritance 30

Defining Attributes and Methods for the Child Class


Inheritance 31

Overriding Methods from the Parent Class


Inheritance 32

Instances as Attributes
Practice 33

9-6,…,9-9
Importing Classes 34

Importing a Single Class Storing Multiple Classes in a Module


Importing Classes 35

Importing Multiple Classes from a Module

Importing Multiple Classes from a Module


Importing Classes 36

Importing Multiple Classes from a Module

Importing Multiple Classes from a Module


Importing Classes 37

Importing a Module into a Module

Using Aliases

You might also like