0% found this document useful (0 votes)
2 views2 pages

Python OOP: Classes, Inheritance, Polymorphism

This document provides Python code examples illustrating key Object-Oriented Programming concepts such as Classes/Objects, Inheritance, Polymorphism, and Iteration. It includes the definition of a Car class, an ElectricCar subclass, and demonstrates polymorphism with Animal subclasses. Additionally, it shows how to iterate through a list using both for and while loops.

Uploaded by

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

Python OOP: Classes, Inheritance, Polymorphism

This document provides Python code examples illustrating key Object-Oriented Programming concepts such as Classes/Objects, Inheritance, Polymorphism, and Iteration. It includes the definition of a Car class, an ElectricCar subclass, and demonstrates polymorphism with Animal subclasses. Additionally, it shows how to iterate through a list using both for and while loops.

Uploaded by

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

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

You might also like