intermediate#python#oop#classes
Understanding Object-Oriented Programming in Python
Learn the basics of object-oriented programming in Python, including classes, objects, inheritance, and polymorphism.
Introduction to OOP
Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of objects and classes.
Classes and Objects
A class is a blueprint for creating objects, and an object is an instance of a class.
# define a class
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def print_details(self):
print(f'Brand: {self.brand}, Model: {self.model}, Year: {self.year}')
# create an object
my_car = Car('Toyota', 'Corolla', 2015)
my_car.print_details()
Inheritance
Inheritance is the process of creating a new class based on an existing class.
# define a subclass
class ElectricCar(Car):
def __init__(self, brand, model, year, battery_capacity):
super().__init__(brand, model, year)
self.battery_capacity = battery_capacity
def print_details(self):
super().print_details()
print(f'Battery Capacity: {self.battery_capacity} kWh')
# create an object
my_electric_car = ElectricCar('Tesla', 'Model S', 2020, 75)
my_electric_car.print_details()