Object-Oriented Programming (OOPs) in Python
Python is an object-oriented programming language, which means it supports concepts like classes, objects, inheritance, polymorphism, encapsulation, and abstraction.
OOP allows developers to structure programs so that properties and behaviors are bundled into objects, making code modular, reusable, and easier to maintain.
πΉ What is OOP?β
- Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects.
- Each object can hold data (attributes) and functions (methods) that operate on that data.
Benefits of OOP in Python:
- Reusability of code
- Encapsulation of data
- Modularity and abstraction
- Easier debugging and maintenance
πΉ Classes and Objectsβ
A class is a blueprint for creating objects.
An object is an instance of a class.
# Defining a class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# Creating objects
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
print(p1.greet()) # Output: Hello, my name is Alice and I am 25 years old.
print(p2.greet()) # Output: Hello, my name is Bob and I am 30 years old.