Python Lab: Object-Oriented Programming (OOP) in Python
This lab will introduce Object-Oriented Programming (OOP) concepts in Python, covering classes,
objects, constructors, attributes, methods, inheritance, and polymorphism.
🔹 Step 1: Creating a Simple Class and Object
A class is a blueprint for creating objects, and an object is an instance of a class.
Task 1: Create a Car class and instantiate an object
class Car:
def __init__(self, brand, color): # Constructor
self.brand = brand # Attribute
self.color = color # Attribute
def drive(self): # Method
print(f"The {self.color} {self.brand} is driving.")
# Creating an object (instance of Car)
my_car = Car("Toyota", "Red")
# Accessing attributes and calling a method
print(my_car.brand) # Output: Toyota
my_car.drive() # Output: The Red Toyota is driving.
🔹 Step 2: Understanding Instance and Class Attributes
Task 2: Add a class attribute and use it
class Car:
wheels = 4 # Class attribute
def __init__(self, brand, color):
self.brand = brand # Instance attribute
self.color = color # Instance attribute
# Creating objects
car1 = Car("Honda", "Blue")
car2 = Car("Ford", "Black")
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
💡 Question:
•
🔹 Step 3: Adding More Methods
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def drive(self):
print(f"The {self.color} {self.brand} is driving.")
def stop(self):
print(f"The {self.brand} has stopped.")
def honk(self):
print(f"{self.brand} is honking! Beep Beep!")
# Creating an object
my_car = Car("Tesla", "White")
# Calling methods
my_car.drive()
my_car.stop()
my_car.honk()
🔹 Step 4: Inheritance (Reusing Code)
Task 4: Create an ElectricCar subclass
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def drive(self):
print(f"The {self.color} {self.brand} is driving.")
# Child class (inherits from Car)
class ElectricCar(Car):
def __init__(self, brand, color, battery_capacity):
super().__init__(brand, color) # Call parent constructor
self.battery_capacity = battery_capacity
def charge(self):
print(f"{self.brand} is charging. Battery: {self.battery_capacity} kWh")
# Creating an object of ElectricCar
my_electric_car = ElectricCar("Tesla", "Blue", 75)
# Accessing methods from the parent class
my_electric_car.drive()
# Calling a method from the ElectricCar class
my_electric_car.charge()
🔹 Step 5: Polymorphism (Method Overriding
Task 5: Override drive() method
python
CopyEdit
class Car:
def drive(self):
print("The car is driving.")
class ElectricCar(Car):
def drive(self): # Overriding method
print("The electric car is driving silently.")
# Creating objects
car1 = Car()
car2 = ElectricCar()
car1.drive() # Output: The car is driving.
car2.drive() # Output: The electric car is driving silently.
💡 Question:
• What if we remove the drive() method in ElectricCar?