Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views8 pages

Lab-9.0. OOP Concepts

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)
13 views8 pages

Lab-9.0. OOP Concepts

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
You are on page 1/ 8

Lab: Object-Oriented Programming (OOP)

Concepts
Duc-Minh VU
FDA - SLSCM Lab
National Economics University
[email protected]
November 23, 2024

Objectives
This lab aims to help you:

• Understand the basic concepts of Object-Oriented Programming (OOP).

1. Object-Oriented Programming (OOP)


Object-Oriented Programming is a programming paradigm where tasks are
solved through collaboration between objects. An object is an entity that
contains:

• Data (attributes).

• Methods (functions) to manipulate the data.

Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print(f"Student Name: {self.name}, Age: {self.age}")

1
# Create an object
student = Student("Minh", 20)
student.display() # Output: Student Name: Minh, Age: 20

2. Class
A class is a blueprint (template) that describes a group of objects with the
same behavior. A class defines how objects:

• Store data.

• Provide methods to manipulate the data.

Example:
class Course:
def __init__(self, course_name):
self.course_name = course_name

def show_course(self):
print(f"Course: {self.course_name}")

# Create an object from the Course class


course = Course("Python Programming")
course.show_course() # Output: Course: Python Programming

3. Methods
Methods are functions defined inside a class and are used to manipulate the
objects of that class.
Example:
class ListExample:
def __init__(self, elements):
self.elements = elements

def add_element(self, element):


self.elements.append(element)

def remove_element(self, element):


self.elements.remove(element)

2
# Create an object and use methods
lst = ListExample([1, 2, 3])
lst.add_element(4) # Add an element
print(lst.elements) # Output: [1, 2, 3, 4]
lst.remove_element(2) # Remove an element
print(lst.elements) # Output: [1, 3, 4]

4. Public Interface
The public interface is the set of all methods a class provides to interact with
its objects. Developers only need to know how to use these methods without
worrying about their implementation.
Example:
# You don’t need to know how .upper() works, only how to use it.
text = "hello"
print(text.upper()) # Output: HELLO

A pure interface in Python can be defined using a class with methods


that have no implementation. This is often used in object-oriented program-
ming to enforce a specific structure or behavior in subclasses.
class Vehicle:
# Public interface with no implementation
def start_engine(self):
pass

def stop_engine(self):
pass

def drive(self):
pass

# Subclass must implement all methods of the interface


class Car(Vehicle):
def start_engine(self):
print("The car engine is starting.")

def stop_engine(self):
print("The car engine is stopping.")

def drive(self):
print("The car is driving.")

3
class Motorcycle(Vehicle):
def start_engine(self):
print("The motorcycle engine is starting.")

def stop_engine(self):
print("The motorcycle engine is stopping.")

def drive(self):
print("The motorcycle is driving.")

# Example usage
vehicles = [Car(), Motorcycle()]

for vehicle in vehicles:


vehicle.start_engine()
vehicle.drive()
vehicle.stop_engine()

Explanation of the Example


1. Pure Interface:
• The Vehicle class acts as a template with methods start engine(),
stop engine(), and drive() defined but not implemented.
2. Subclass Implementation:
• The Car and Motorcycle classes inherit from Vehicle and provide
specific implementations for all the methods.
3. Behavior Enforcement:
• All subclasses are required to implement the public interface de-
fined in the Vehicle class.

Output of the Example


The car engine is starting.
The car is driving.
The car engine is stopping.
The motorcycle engine is starting.
The motorcycle is driving.
The motorcycle engine is stopping.

4
5. Encapsulation
Encapsulation is the process of hiding the implementation details of a class
and providing only a public interface for users to interact with the object.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")

def get_balance(self):
return self.__balance

# Create an object
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
print(account.get_balance()) # Output: 1200

Exercises
Exercise 1: Defining a Simple Class
Complete the following code to create a simple Dog class with:
• An attribute name (public).

• A method bark() that prints ”{name} says Woof!”.


Template:
class Dog:
def __init__(self, ________):
self.________ = ________

5
def ________(self):
print(f"{self.________} says Woof!")

# Usage
dog = Dog("Buddy")
dog.bark()

Expected Output:

Buddy says Woof!

Exercise 2: Defining a Public Interface


Complete the following code to define a Calculator class with a public
interface for basic operations:

• add(a, b): Returns the sum of a and b.

• subtract(a, b): Returns the difference between a and b.

• multiply(a, b): Returns the product of a and b.

• divide(a, b): Returns the quotient of a divided by b, or "Cannot


divide by zero" if b == 0.

Template:
class Calculator:
def add(self, a, b):
return ________

def subtract(self, a, b):


return ________

def multiply(self, a, b):


return ________

def divide(self, a, b):


if ________:
return "Cannot divide by zero"
return ________

# Usage
calc = Calculator()
print(calc.add(10, 5)) # 15

6
print(calc.subtract(10, 5)) # 5
print(calc.multiply(10, 5)) # 50
print(calc.divide(10, 0)) # Cannot divide by zero
print(calc.divide(10, 2)) # 5

Expected Output:

15
5
50
Cannot divide by zero
5

Exercise 3: Defining an Interface Template for Shapes


Complete the following code to define a public interface Shape with:

• A method area() (no implementation).

• A method perimeter() (no implementation).

Then, create a Rectangle class that implements this interface with at-
tributes:

• length.

• width.

Template:
class Shape:
def area(self):
________

def perimeter(self):
________

class Rectangle(Shape):
def __init__(self, length, width):
self.________ = length
self.________ = width

def area(self):
return ________

7
def perimeter(self):
return ________

# Usage
rect = Rectangle(5, 3)
print(rect.area()) # 15
print(rect.perimeter()) # 16

Expected Output:

15
16

Conclusion
Object-Oriented Programming is an efficient approach to organize and man-
age code in complex projects. By using:

• Classes to define behavior.

• Objects to store data and perform actions.

• Methods to interact with data.

• Encapsulation to protect implementation details.

you can build scalable and maintainable programs.

You might also like