Object-Oriented Programming (OOP)

OOP is a programming paradigm based on the concept of "objects," which can contain data and code. It helps in organizing complex software systems.

1. Defining a Class

A class is a blueprint for creating objects. Use PascalCase for class names.

class Robot:
    def __init__(self, name, model):
        self.name = name   # Instance Variable
        self.model = model

    def introduce(self):
        print(f"Hi, I am {self.name}, model {self.model}.")

# Creating an Object
r1 = Robot("R2D2", "Astromech")
r1.introduce()

2. Attributes and Methods

  • __init__: The constructor method. It runs automatically when an object is created.
  • self: Represents the instance of the class itself.

3. Class vs Instance Variables

class Car:
    wheels = 4 # Class variable (shared by all)

    def __init__(self, make):
        self.make = make # Instance variable

4. The Power of OOP

OOP allows you to model real-world concepts more naturally. Instead of just variables, you have entities with their own behaviors (methods) and state (attributes).

Modular Design: Professional Python libraries (like Pandas or Django) are built entirely on OOP principles.