Introduction to OOP in Python

Introduction to OOP in Python

Object-Oriented Programming (OOP) is a programming paradigm that organizes code using objects and classes. It helps in structuring code in a modular and reusable way.

Key Concepts of OOP:

  1. Class – A blueprint for creating objects.
  2. Object – An instance of a class.
  3. Attributes – Variables that store data for an object.
  4. Methods – Functions defined inside a class that operate on object attributes.
  5. Encapsulation – Restricting access to certain details of an object.
  6. Inheritance – Allowing a class to inherit features from another class.
  7. Polymorphism – Allowing objects to be treated as instances of their parent class.

Why Use OOP?

  • Modularity: Code is structured into reusable components.
  • Reusability: Code can be extended without modifying existing functionality.
  • Scalability: Helps in managing large codebases.
  • Data Protection: Encapsulation restricts direct access to data.

Defining a Simple Class and Object in Python

class Car:
    def __init__(self, brand, model):
        self.brand = brand  # Attribute
        self.model = model  # Attribute
    
    def display_info(self):
        return f"Car: {self.brand} {self.model}"

# Creating an object
my_car = Car("Toyota", "Corolla")
print(my_car.display_info())  # Output: Car: Toyota Corolla