0% found this document useful (0 votes)
11 views6 pages

Lab-9.1. Class in Python

OOP in Python

Uploaded by

nghonganh016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Lab-9.1. Class in Python

OOP in Python

Uploaded by

nghonganh016
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lab: Classes in Python

Duc-Minh VU
FDA - SLSCM Lab
National Economics University
minhvd@[Link]
November 23, 2024

Objectives
After completing this lab, students will achieve the following objectives:

• Understand the concept of classes and objects in Object-Oriented Pro-


gramming (OOP).

• Know how to declare, initialize a class, and create objects in Python.

• Proficiently use the basic components of a class, including:

– Constructor ( init ()).


– Attributes and methods.
– The self keyword.

• Apply knowledge of classes and objects to solve real-world problems.

• Strengthen skills in writing Python code following the OOP paradigm.

1 Classes in Python
A Class in Python is a template used to define the structure and behav-
ior (attributes and methods) of objects. It is a core component of Object-
Oriented Programming (OOP), enabling efficient organization and reuse of
code.

1
1.1 Structure of a Class
A class in Python includes:

• Class Name: Defined using the class keyword.

• Constructor: The special method init () used to initialize at-


tributes.

• Attributes: Variables that represent the state of an object.

• Methods: Functions that define the behavior of an object.

• The self keyword: Represents the current instance of the class, used
to access attributes and methods.

1.2 Class Declaration Syntax


The general structure of a class is as follows:
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1 # Declare attributes
self.attribute2 = attribute2

def method1(self):
# Perform an action
pass

def method2(self, param):


# Perform an action with a parameter
pass

2 Illustrative Examples
2.1 Basic Class
class Car:
def __init__(self, brand, model, year):
[Link] = brand # Attribute: car brand
[Link] = model # Attribute: car model
[Link] = year # Attribute: manufacture year

2
def display_info(self):
print(f"Car: {[Link]} {[Link]}, Year: {[Link]}")

Explanation:
• The Car class has three attributes: brand, model, and year.

• The init () constructor initializes the attribute values when creat-


ing an object.

• The display info() method prints the car’s information as a string.


Using the class:
# Create objects
car1 = Car("Toyota", "Camry", 2021)
car2 = Car("Honda", "Civic", 2020)

# Call methods
car1.display_info()
car2.display_info()

2.2 Class with Behavior


class Circle:
def __init__(self, radius):
[Link] = radius # Attribute: radius

def area(self):
# Calculate area
return 3.14 * [Link] ** 2

def circumference(self):
# Calculate circumference
return 2 * 3.14 * [Link]

Explanation:
• The Circle class has a single attribute, radius.

• The area() method calculates the area of the circle using the formula
S = πr2 .

• The circumference() method calculates the circumference using C =


2πr.

3
Using the class:
circle1 = Circle(5)

# Call methods
print("Area:", [Link]())
print("Circumference:", [Link]())

3 Practical Exercises
Exercise 1: Student Management
Description: Complete the implementation of the Student class by filling
in the blanks to meet the requirements below:
The Student class should have the following:

• Attributes: name (student name), student id (student ID), and grades


(a list of grades).

• Methods:

– add grade(grade): Add a new grade to the list.


– average(): Calculate the student’s average grade.
– display(): Display student information and their average grade.

Template:
class Student:
def __init__(self, name, student_id):
self.________ = name
self.________ = student_id
self.________ = [] # Initialize grades as an empty list

def add_grade(self, grade):


self.________.append(grade)

def average(self):
if self.________:
return sum(self.________) / len(self.________)
return 0

def display(self):
print(f"Name: {self.________}, ID: {self.________}")

4
print(f"Average Grade: {self.________():.2f}")

# Usage
student = Student("Alice", "S123")
student.add_grade(85)
student.add_grade(90)
student.add_grade(78)
[Link]()

Expected Output:
Name: Alice, ID: S123
Average Grade: 84.33

Exercise 2: Rectangle
Description: Create a Rectangle class with the following attributes:
• width
• height
Add the following methods:
• area(): Calculate the area using width * height.
• perimeter(): Calculate the perimeter using 2 * (width + height).
• compare area(other rectangle): Compare the area with another
rectangle.

Exercise 3: Bank Account Simulation


Description: Create a BankAccount class with the following attributes:
• account number
• balance (default is 0)
Add the following methods:
• deposit(amount): Add money to the account. If amount is less than
or equal to 0, print an error message.
• withdraw(amount): Withdraw money. If the amount exceeds the bal-
ance, print an error message.
• display balance(): Display the current balance.

5
4 Summary
• Class: A template for defining the attributes and behavior of objects.

• Object: A specific instance created from a class.

• Class declaration involves:

– Using the class keyword.


– Initializing attributes through the init () method.
– Defining behavior through methods.

You might also like