OOP Concepts and Python Implementation
OOP Concepts and Python Implementation
College of Engineering
Electronics Engineering Department
Activity 5
OBJECT-ORIENTED PROGRAMMING (OOP)
I. INTRODUCTION
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into reusable objects
that represent real-world entities. In Python, OOP enhances code modularity, maintainability, and scalability by
defining classes as blueprints for objects. A class encapsulates attributes (data) and methods (functions) that
define the object's behavior, allowing for more structured and reusable code.
Key OOP principles include encapsulation, which restricts direct access to an object’s data, ensuring
controlled modification; inheritance, which enables new classes to reuse and extend the functionality of existing
ones; and polymorphism, which allows different objects to be used interchangeably while maintaining consistent
behavior. Python also supports method overriding and advanced OOP features, allowing developers to tailor class
behaviors for specific use cases.
This lab will introduce students to creating and working with classes and objects, implementing core OOP
principles, and utilizing Python’s built-in object-oriented libraries. Through hands-on exercises, students will
develop a deeper understanding of OOP design patterns, improving their ability to write scalable, efficient, and
well-structured programs.
def method(self):
print("This is a method.")
# Creating an object
object_name = ClassName(value1, value2)
object_name.method() # Calling a method
def get_value(self):
return self. private_attribute # Controlled access method
# Creating an object
obj = ClassName(initial_value)
print(obj.get_value()) # Accessing private data via method
obj.set_value(new_value)
class ChildClass(ParentClass):
pass # Inherits all methods from ParentClass
class ClassB:
def action(self):
print("Action from ClassB.")
# Polymorphic function
def execute_action(obj):
[Link]() # Calls the respective action method
# Creating objects
Evaluation Copy 2
Strictly for TUP ECE students only
obj1 = ClassA()
Evaluation Copy 3
Strictly for TUP ECE students only
obj2 = ClassB()
class ChildClass(ParentClass):
def method(self): # Overriding the parent method
print("Overridden method from ChildClass.")
III. PROCEDURES
1. Creating a Class and Object in Python
# Step 1: Define a class named
Car class Car:
def init (self, brand, model,
year): [Link] = brand
[Link] =
model [Link]
= year
Evaluation Copy 4
Strictly for TUP ECE students only
def display_info(self):
return f"{[Link]} {[Link]} {[Link]}"
Evaluation Copy 5
Strictly for TUP ECE students only
# Step 2: Create an object of the Car class
my_car = Car("Toyota", "Corolla", 2022)
Task:
Create a class Laptop with attributes brand, processor, and ram.
Define a method get_specs() that returns a formatted string of the laptop's specifications.
Create an object of Laptop, assign values, and print the specifications.
def get_balance(self):
return f"Balance: ${self. balance}"
Task:
Create a class StudentRecord with a private attribute grades.
Implement methods to add a grade and retrieve the list of grades.
Test encapsulation by adding grades and printing the list.
def introduce(self):
return f"Hi, I'm {[Link]}."
Evaluation Copy 6
Strictly for TUP ECE students only
student = Student("Mark")
print([Link]())
print([Link]())
Task:
Create a base class Device with an attribute device_name and a method power_on().
Create a subclass Smartphone that overrides power_on() to display a custom message.
Create objects of both classes and call their methods.
4. Utilizing Polymorphism in
Python # Step 1: Define a
base class class Shape:
def area(self):
return "Calculating area..."
def area(self):
return 3.14 * [Link] * [Link]
class Rectangle(Shape):
def init (self, length,
width): [Link] =
length [Link] = width
def area(self):
return [Link] * [Link]
Task:
● Create a base class Device with a method power_on().
● Create two subclasses: Smartphone and Laptop, both overriding power_on() to
display different startup messages.
● Write a function start_device(device) that takes a Device object and calls its
power_on() method.
● Create objects of Smartphone and Laptop, then pass them to start_device()
to demonstrate polymorphism.
Task:
● Import the random module and generate a random floating-point number between 0
and 1.
● Import the os module and print the name of the operating system.
Task:
● Create a class TemperatureConverter with a static method
celsius_to_fahrenheit(celsius).
● Prompt the user to input a temperature in Celsius.
● Use the method to convert the user-provided Celsius temperature to Fahrenheit.
● Print the converted temperature.
Evaluation Copy 8
Strictly for TUP ECE students only
Task:
● Create a class Vector with overloaded + and - operators.
Evaluation Copy 9
Strictly for TUP ECE students only
● Perform vector addition and subtraction using instances of the class.
Task:
● Create another subclass Refrigerator that inherits from Appliance.
● Implement the turn_on() method to return "Refrigerator is now cooling."
● Create an object of Refrigerator and call its turn_on() method.
class B(A):
def show(self):
return "Class
B"
class C(A):
def show(self):
return "Class
C"
Evaluation Copy 1
Strictly for TUP ECE students only 0
Task:
● Create four classes that follow multiple inheritance.
● Implement show() in each and observe the output of MRO using print([Link]()).
10. Debugging Exercises
Each code snippet contains an error. Debug and correct them.
Evaluation Copy 1
Strictly for TUP ECE students only 1
1. class Person:
def init (self, name):
name = name
p = Person("Allen")
print([Link])
2. class Vehicle:
def init (self, brand):
[Link] = brand
class Car(Vehicle):
def init (self, brand, model):
[Link] = model
3. class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def
speak(self):
"Bark!"
d = Dog()
print([Link]())
4. class BankAccount:
def init (self,
balance):
[Link] =
balance
account1 =
BankAccount(500)
account2 =
BankAccount(300) total =
account1 + account2
print([Link])
5. class Store:
def calculate_discount(price, discount):
return price - (price * discount /
100)
store_instance = Store()
print(Store.calculate_discount(100,
10))
Evaluation Copy 1
Strictly for TUP ECE students only 2
IV. DATA AND OBSERVATION
def get_balance(self):
return f"Balance: {self. balance}"
Evaluation Copy 13
Strictly for TUP ECE students only
4 class Animal: Bark! Method
def speak(self): overriding
return "Some works properly
sound"
in the subclass
class Dog(Animal): Dog.
def
speak(self):
return "Bark!"
dog = Dog()
print([Link]())
5 class Vehicle: Vehicle is moving Inheritance is
def move(self): Uses electricity correctly
return "Vehicle is moving" implemented, and
method
class Car(Vehicle):
overriding in
def fuel_type(self):
ElectricCar
return "Uses
gasoline" works fine.
class ElectricCar(Car):
def
fuel_type(self):
return "Uses electricity"
tesla = ElectricCar()
print([Link]())
print(tesla.fuel_type())
6 class Device: Smartphone is Method
def power_on(self): booting up overriding in
return "Device is turning on" Smartphone works
as expected.
class
Smartphone(Device):
def power_on(self):
return "Smartphone is booting up"
phone = Smartphone()
print(phone.power_on())
Evaluation Copy 14
Strictly for TUP ECE students only
7 class Box: AttributeError 'int' object has
def init (self, weight): no attribute
[Link] = weight 'weight'
def add (self, other):
return [Link] + [Link]
box1 = Box(5)
box2 = Box(10)
box3 = box1 +
box2
print(f"Total weight: {[Link]} kg")
8 from abc import ABC, abstractmethod Fan is spinning Abstract class
Appliance is
class
properly used
Appliance(ABC):
@abstractmethod with an
def implemented
turn_on(self): method in Fan.
pass
class Fan(Appliance):
def turn_on(self):
return "Fan is spinning"
fan = Fan()
print(fan.turn_on())
9 class Engine: Engine started Multiple
def start(self): Wheels rolling inheritance works
return "Engine started" Car is moving correctly,
calling methods
class Wheels:
def roll(self): from Engine and
return "Wheels rolling" Wheels.
class Car(Engine,
Wheels): def
drive(self):
return "Car is moving"
my_car = Car()
print(my_car.start())
print(my_car.roll())
print(my_car.drive())
Evaluation Copy 15
Strictly for TUP ECE students only
10 class Enter a number: 5 The static
MathOperations: Square: 25 method square()
@staticmethod correctly
def square(num):
computes the
return num * num
square of an
number = int(input("Enter a number: ")) input number.
print("Square:", [Link](number))
book1 = Book("1984")
print(book1.get_info())
12 class Product: Laptop costs $1200 Product details
def init (self, name, display correctly.
price): [Link] =
name [Link] = price
def get_details(self):
return f"{[Link]} costs $
{[Link]}"
p = Person("Alice")
print([Link]())
14 class ATM: Withdrawn 200, Withdraw
def init (self, balance): Remaining balance: functionality
[Link] = balance 800 works correctly.
Evaluation Copy 16
Strictly for TUP ECE students only
def withdraw(self,
amount): if amount >
[Link]:
return "Insufficient balance"
[Link] -= amount
return f"Withdrawn {amount}, Remaining
balance: {[Link]}"
atm = ATM(1000)
print([Link](200))
def get_info(self):
return f"Patient: {[Link]}, Age:
{[Link]}, Disease: {[Link]}"
def teach(self):
return f"{[Link]} is teaching
{[Link]}"
Evaluation Copy 17
Strictly for TUP ECE students only
18 class Flight: TypeError Flight. init ()
def init (self, flight_number, missing 1
destination): self.flight_number = required
flight_number [Link] = positional
destination argument:
'destination'
def book_ticket(self):
return f"Ticket booked for flight
{self.flight_number} to {[Link]}"
flight1 = Flight(101)
print(flight1.book_ticket())
def turn_on(self):
[Link] =
"On"
return f"{self.device_name} is now
{[Link]}"
def show_books(self):
return f"Available Books: {',
'.join([Link])}"
library = Library()
print(library.add_book("Python
Programming")) print(library.show_books())
Evaluation Copy 18
Strictly for TUP ECE students only
[Link] AND INTERPRETATION
1. How does encapsulation help in data security and code maintainability in Python's object-
oriented programming? Provide an example to illustrate its importance.
Encapsulation enhances security by restricting direct access to object attributes, ensuring controlled
modifications through methods. This maintains data integrity and simplifies debugging. For example, a bank
account class uses private attributes with deposit() and withdraw() methods to prevent unauthorized
balance changes.
2. In what scenarios would you prefer composition over inheritance when designing a Python application?
Explain your reasoning with a real-world example.
Composition is preferred when flexibility is needed, avoiding rigid inheritance structures. Instead of inheriting, a
class contains objects of other classes, promoting modularity. For instance, a Car class can have an Engine
object, allowing different cars to use various engines without modifying the main class.
3. How does method overriding in polymorphism improve code flexibility, and how does it differ from
method overloading in other programming languages?
Method overriding allows subclasses to redefine inherited methods, improving flexibility. Unlike method
overloading in other languages, Python uses default and variable-length arguments to achieve similar results.
Overriding ensures objects behave appropriately based on their actual type, essential for polymorphism.
VI. DISCUSSION
Method overriding supports polymorphism, ensuring subclass methods can modify inherited behavior for better
customization. Together, these principles improve software design, making applications more scalable and easier
to manage. Encapsulation, composition, and method overriding are fundamental object-oriented programming
principles that enhance security, flexibility, and maintainability in Python applications. Encapsulation protects
data by restricting direct access and enforcing controlled interactions, reducing errors and improving debugging.
Composition promotes modularity by allowing objects to contain other objects, making code reusable and
adaptable to changes without modifying the main class structure.
VII. CONCLUSION
Mastering these concepts helps developers write cleaner, reusable, and well-structured code, essential for building
scalable applications. Understanding and applying encapsulation, composition, and method overriding in Python
leads to more secure, maintainable, and flexible software development. Encapsulation safeguards sensitive data,
composition enhances code modularity, and overriding methods improve object-specific behavior, ensuring
efficient and adaptable programs.
VIII. REFERENCES
[Link]. (n.d.). [Link]
IX. EXERCISES
Functionality:
Develop a program that allows a library to manage books, including adding new books,
borrowing, and returning them.
Evaluation Copy 19
Strictly for TUP ECE students only
Input:
Evaluation Copy 20
Strictly for TUP ECE students only
● The user enters the number of books to add.
● For each book, the user provides a title, author, and availability status.
● The user can borrow a book by entering its title.
● The user can return a borrowed book.
Calculations:
● Keep track of which books are available, and which are borrowed.
● Ensure that a book cannot be borrowed if it is checked out.
Output:
● Display the list of books with their status (available/borrowed).
● Confirm when a book is successfully borrowed or returned.
Functionality:
Create a payroll system that calculates the monthly salary of employees based on their hourly
rate and hours worked.
Input:
● The user enters the number of employees.
● For each employee, the user provides a name, hourly wage, and total hours worked.
Calculations:
● Compute the monthly salary as:
Salary = Hourly Rate × Hours Worked
● If an employee works over 160 hours, calculate overtime pay at 1.5× the hourly rate
for extra hours.
Output:
● Display each employee’s name, total hours worked, base salary, and overtime pay
if applicable.
Functionality:
Develop a shopping cart system where users can add products, remove them, and view the
total price.
Input:
● The user selects products to add from a predefined list.
Evaluation Copy 21
Strictly for TUP ECE students only
● Each product has a name, price, and stock quantity.
● The user can remove items from the cart before checkout.
Calculations:
● Keep track of total cost as items are added/removed.
● Ensure stock availability before adding a product.
Output:
● Display the cart’s content with the total price.
● Confirm when an item is successfully added or removed.
Evaluation Copy 22
Strictly for TUP ECE students only
X. APPENDICES
Appendix A: Screenshots of Program Outputs
(Attach sample screenshots of your outputs here.)
Evaluation Copy 23
Strictly for TUP ECE students only
Evaluation Copy 24
Strictly for TUP ECE students only
Evaluation Copy 25
Strictly for TUP ECE students only
Evaluation Copy 26
Strictly for TUP ECE students only
Evaluation Copy 27
Strictly for TUP ECE students only
Evaluation Copy 28
Strictly for TUP ECE students only
Evaluation Copy 29
Strictly for TUP ECE students only
Evaluation Copy 30
Strictly for TUP ECE students only
Evaluation Copy 31
Strictly for TUP ECE students only
Evaluation Copy 32
Strictly for TUP ECE students only
Evaluation Copy 33
Strictly for TUP ECE students only
Appendix B: Complete Python Code for All Procedures
Evaluation Copy 34
Strictly for TUP ECE students only
Evaluation Copy 35
Strictly for TUP ECE students only
Evaluation Copy 36
Strictly for TUP ECE students only
Evaluation Copy 37
Strictly for TUP ECE students only
Evaluation Copy 38
Strictly for TUP ECE students only
Evaluation Copy 39
Strictly for TUP ECE students only
Appendix C: Complete Python Code for All Exercises
Evaluation Copy 40
Strictly for TUP ECE students only
Evaluation Copy 41
Strictly for TUP ECE students only
Evaluation Copy 42
Strictly for TUP ECE students only
Evaluation Copy 43
Strictly for TUP ECE students only
Evaluation Copy 44
Strictly for TUP ECE students only
Evaluation Copy 45
Strictly for TUP ECE students only
Evaluation Copy 46
Strictly for TUP ECE students only
Evaluation Copy 47
Strictly for TUP ECE students only
Evaluation Copy 48
Strictly for TUP ECE students only
Evaluation Copy 49
Strictly for TUP ECE students only
Evaluation Copy 50
Strictly for TUP ECE students only
Evaluation Copy 51
Strictly for TUP ECE students only
Evaluation Copy 52
Strictly for TUP ECE students only
Evaluation Copy 53
Strictly for TUP ECE students only
Evaluation Copy 54
Strictly for TUP ECE students only
Evaluation Copy 55
Strictly for TUP ECE students only
Evaluation Copy 56
Strictly for TUP ECE students only
Evaluation Copy 57
Strictly for TUP ECE students only
Evaluation Copy 58
Strictly for TUP ECE students only
Evaluation Copy 59
Strictly for TUP ECE students only
Evaluation Copy 60
Strictly for TUP ECE students only
Evaluation Copy 61
Strictly for TUP ECE students only
Evaluation Copy 62
Strictly for TUP ECE students only