Python Assignment - Polymorphism, Iteration, Inheritance,
Classes/Objects
This document contains Python code demonstrating key Object-Oriented Programming
(OOP) concepts including Classes/Objects, Inheritance, Polymorphism, and Iteration.
# **1. Classes and Objects**
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def show_details(self):
print(f"Car Brand: {[Link]}, Model: {[Link]}")
# Object Creation
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")
car1.show_details()
car2.show_details()
# **2. Inheritance**
class ElectricCar(Car): # Inheriting from Car class
def __init__(self, brand, model, battery_capacity):
super().__init__(brand, model)
self.battery_capacity = battery_capacity
def show_battery(self):
print(f"Battery Capacity: {self.battery_capacity} kWh")
# Object of Child Class
e_car = ElectricCar("Tesla", "Model S", 100)
e_car.show_details()
e_car.show_battery()
# **3. Polymorphism**
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self):
print("Dog barks")
class Cat(Animal):
def make_sound(self):
print("Cat meows")
# Polymorphism in action
animals = [Dog(), Cat(), Animal()]
for animal in animals:
animal.make_sound()
# **4. Iteration**
numbers = [1, 2, 3, 4, 5]
print("Using for loop:")
for num in numbers:
print(num)
print("Using while loop:")
i=0
while i < len(numbers):
print(numbers[i])
i += 1