Object-Oriented Programming Fundamentals
Object-Oriented Programming (OOP) is a programming paradigm that focuses on the use of objects to design and implement software applications. In Python, OOP is a powerful tool that allows you to create reusable and maintainable code.
Classes and Objects
The fundamental building blocks of OOP are classes and objects. A class is a blueprint or template that defines the properties (attributes) and behaviors (methods) of an object. An object is an instance of a class.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start(self):
print("Starting the car.")
def stop(self):
print("Stopping the car.")
my_car = Car("Toyota", "Camry", 2020)
my_car.start() ## Output: Starting the car.
my_car.stop() ## Output: Stopping the car.
Inheritance
Inheritance is a mechanism that allows you to create a new class based on an existing class. The new class inherits the attributes and methods of the existing class, and can also add or modify them.
class ElectricCar(Car):
def __init__(self, make, model, year, battery_capacity):
super().__init__(make, model, year)
self.battery_capacity = battery_capacity
def charge(self):
print("Charging the electric car.")
my_electric_car = ElectricCar("Tesla", "Model S", 2022, 100)
my_electric_car.start() ## Output: Starting the car.
my_electric_car.charge() ## Output: Charging the electric car.
Polymorphism
Polymorphism is the ability of objects of different classes to be treated as objects of a common superclass. This allows you to write more generic and flexible code.
def drive(vehicle):
vehicle.start()
vehicle.stop()
drive(my_car) ## Output: Starting the car., Stopping the car.
drive(my_electric_car) ## Output: Starting the car., Charging the electric car.
Encapsulation
Encapsulation is the principle of hiding the internal implementation details of an object from the outside world. This is achieved through the use of access modifiers, such as public
, private
, and protected
.
class BankAccount:
def __init__(self, owner, balance):
self.__owner = owner
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if self.__balance >= amount:
self.__balance -= amount
else:
print("Insufficient funds.")
account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200) ## Output: 1300
account.__balance = -500 ## This will not work due to encapsulation
These OOP concepts, along with others like abstract classes, interfaces, and decorators, provide a powerful way to write modular, extensible, and maintainable Python code.