Welcome to this tutorial on object-oriented programming (OOP)! OOP is a fundamental concept in software development, allowing you to model real-world objects and their interactions in code. This tutorial will cover the basics of OOP, including classes, objects, inheritance, and polymorphism.
Classes and Objects
The building blocks of OOP are classes and objects. A class is a blueprint for creating objects, which are instances of a class.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def drive(self):
print(f"The {self.year} {self.make} {self.model} is driving.")
Creating Objects
To create an object, you use the class name followed by parentheses:
my_car = Car("Toyota", "Corolla", 2020)
Inheritance
Inheritance allows you to create a new class (derived class) based on an existing class (base class). This allows you to reuse and extend the functionality of the base class.
class ElectricCar(Car):
def __init__(self, make, model, year, battery_size):
super().__init__(make, model, year)
self.battery_size = battery_size
def charge(self):
print(f"Charging the {self.year} {self.make} {self.model} with a battery size of {self.battery_size} kWh.")
Extending Classes
You can extend the ElectricCar
class with additional functionality specific to electric cars.
class HybridCar(Car):
def __init__(self, make, model, year, engine_size, battery_size):
super().__init__(make, model, year)
self.engine_size = engine_size
self.battery_size = battery_size
def drive(self):
if self.battery_size > 0:
print(f"The {self.year} {self.make} {self.model} is driving on battery power.")
else:
print(f"The {self.year} {self.make} {self.model} is driving on engine power.")
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. This is particularly useful when you want to write code that operates on a group of objects without needing to know their specific types.
def display_make_and_model(car):
print(f"Make: {car.make}, Model: {car.model}")
my_cars = [my_car, electric_car, hybrid_car]
for car in my_cars:
display_make_and_model(car)
For more information on object-oriented programming, check out our comprehensive guide on OOP Fundamentals.