Object-Oriented Programming (OOP) is a way of structuring programs around objects — bundles of data (attributes) and behavior (methods). It helps make code more modular, reusable, and easier to maintain, especially in larger projects.
__init__() – A special method (constructor) called when an object is created.self – Refers to the current object instance; used to access attributes and methods.A simple class in Python looks like this conceptually:
class → blueprint object → real thing
Basic structure:
class keyword to define a class.__init__() to initialize attributes.self as the first parameter.p1 = Person("Alice", 25).A class is like a blueprint for creating objects. Objects are instances of a class, each with its own data.
class Person:
def __init__(self, name, age):
# Constructor
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create object
p1 = Person("Alice", 25)
p1.greet()
The __init__() method is called automatically whenever a new object is created. It is used to initialize object attributes (similar to a constructor in other languages).
The self parameter in methods refers to the current object instance. Using self, you can read and update the object's attributes and call its other methods.
Methods are functions defined inside a class that operate on its objects. They usually use self to access or modify the object's data.
class Car:
# Define a Car class
def __init__(self, brand, year):
# Initialize car attributes
self.brand = brand
self.year = year
def display(self):
# Method to display car info
print(f"{self.brand} car was manufactured in {self.year}")
# Create a Car object
car1 = Car("Toyota", 2020)
# Call the display method
car1.display()
For the Person class:
p1 = Person("Alice", 25) creates an object with name = "Alice" and age = 25.p1.greet() prints:Hello, my name is Alice and I am 25 years old.For the Car class:
car1 = Car("Toyota", 2020) sets brand = "Toyota" and year = 2020.car1.display() prints:Toyota car was manufactured in 2020Notice how each object remembers its own data, and methods use that data to produce meaningful output.
self as the first parameter in instance methods.Student, Invoice, Order).Student class with attributes name and grade, and a method to display the details.Book class with title and author, then create two objects and print their details.Rectangle with length and width, and a method to calculate and return the area.