Professional Documents
Culture Documents
Programming (OOP)
Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects", which can contain data in the form of attributes and code in the form of methods.
Python is an object-oriented language, which means it supports OOP principles.
class Car:
self.make = make
self.model = model
self.year = year
def display_info(self):
car1.display_info()
car2.display_info()
Inheritance is one of the fundamental concepts in object-oriented programming (OOP). It allows
a new class to inherit attributes and methods from an existing class, promoting code reuse and
facilitating the creation of specialized classes. In Python, inheritance is achieved by specifying
the parent class(es) in the definition of a subclass.
4. Multiple Inheritance:
• Python supports multiple inheritance, where a subclass can inherit from multiple
superclasses. However, it's recommended to use multiple inheritance cautiously
due to potential complexity and ambiguity.
5. Method Overriding:
• Subclasses can override methods of the superclass by redefining them in the
subclass. This allows for customizing the behavior of inherited methods in the
subclass.
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Animal speaks")
# Child class inheriting from Animal
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
print(f"{cat.name} is {cat.color}")
cat.speak()
Example:
class ElectricCar(Car):
def __init__(self, make, model, year, battery_capacity):
super().__init__(make, model, year)
self.battery_capacity = battery_capacity
def display_info(self):
super().display_info()
print(f"Battery Capacity: {self.battery_capacity} kWh")
Instructions:
1. Define a parent class called Animal with the following attributes and methods:
• Attributes:
• Methods:
2. Create two subclasses Dog and Cat inheriting from the Animal class. Implement the following:
• Dog class:
• Attributes:
• Methods:
• Cat class:
• Attributes:
• Methods:
3. Instantiate objects of the Dog and Cat classes with appropriate attributes and call the speak()
method for each object to display their respective sounds.
Example:
Example:
# Define the Vehicle, EngineType, FuelType, and Car classes as instructed.
# Create objects of Car class
car1 = Car("Toyota", "Camry", "Gasoline", "Petrol")
car2 = Car("Tesla", "Model 3", "Electric", "Electricity")
• Ensure that the display_info() method in the Car class overrides the method in the
parent class (Vehicle) to include information about the engine type and fuel type.
• Test your implementation with different instances of Car objects to verify the
correctness of the behavior.