So far your programs have been functions operating on plain data. Object-oriented programming (OOP) bundles related data and the functions that work on it into a single unit — a class. It's how you model real things (a Student, an Account, a Programme) and the backbone of almost every large Python codebase and framework you'll use.
Why OOP?
When you find yourself passing the same bundle of related values into function after function, that bundle wants to be an object. A class keeps the data and its behaviour together, so callers work with a clean interface instead of loose variables. It gives you reuse (inheritance), safety (encapsulation) and readable, self-documenting code.
Classes & objects
A class is a blueprint; an object (or instance) is a thing built from it. Define a class with class (PascalCase name by convention), then create instances by calling it like a function:
class Student:passa = Student() # an instanceb = Student() # a different instanceprint(type(a)) # <class '__main__.Student'>
__init__ & self
__init__ is the constructor — it runs automatically when you create an instance, and sets up its data. self is the instance being built; every method takes it as the first parameter so it can read and write that object's attributes:
class Student:def __init__(self, name, programme):self.name = name # instance attributesself.programme = programmeself.placed = Falseaanya = Student("Aanya", "Data Analytics")print(aanya.name) # Aanyaaanya.placed = True # attributes are just data you can read/write
Methods
A method is a function defined inside a class; it acts on the instance via self:
class Student:def __init__(self, name, package=0):self.name = nameself.package = packagedef give_raise(self, pct):self.package *= 1 + pct / 100def summary(self):return f"{self.name}: ₹{self.package:.1f} LPA"s = Student("Rohan", 8)s.give_raise(25)print(s.summary()) # Rohan: ₹10.0 LPA
Inheritance
A class can inherit from another, gaining its attributes and methods and adding or overriding its own. Use super() to call the parent's version — this is how you specialise a general class:
class Person:def __init__(self, name):self.name = namedef greet(self):return f"Hi, I'm {self.name}"class Student(Person): # Student IS-A Persondef __init__(self, name, programme):super().__init__(name) # run Person's __init__self.programme = programmedef greet(self): # overridereturn f"{super().greet()}, studying {self.programme}"print(Student("Priya", "Full Stack").greet())# Hi, I'm Priya, studying Full Stack
Encapsulation & properties
Python has no truly private attributes, but a leading underscore (_balance) signals "internal — don't touch from outside". When you need controlled access, a @property exposes a method as if it were an attribute, letting you validate on set:
class Account:def __init__(self, balance=0):self._balance = balance@propertydef balance(self): # read like an attribute: acc.balancereturn self._balance@balance.setterdef balance(self, value):if value < 0:raise ValueError("balance can't be negative")self._balance = valueacc = Account()acc.balance = 500 # goes through the setter (validated)print(acc.balance) # 500
Dunder methods
Double-underscore ("dunder") methods let your objects work with Python's built-in syntax. Define __str__ for a readable print, __eq__ for ==, __len__ for len(), and more:
| Dunder | Enables |
|---|---|
__init__ | Construction: Student(...) |
__str__ | str(obj) / print(obj) |
__repr__ | The debug representation |
__eq__ | obj1 == obj2 |
__len__ | len(obj) |
class Batch:def __init__(self, students):self.students = studentsdef __len__(self):return len(self.students)def __str__(self):return f"Batch of {len(self)}"b = Batch(["Aanya", "Rohan"])print(len(b)) # 2print(b) # Batch of 2
Practice
Build a Programme class with a name, duration and fee, a method that applies a discount, and a __str__. Then subclass it as FlagshipProgramme that adds a mentor and overrides the summary — using super().
Key takeaways
- 01A class bundles related data (attributes) and behaviour (methods) into one type.
- 02__init__ is the constructor; self is the current instance every method receives first.
- 03Inheritance reuses and specialises a class; super() calls the parent version.
- 04A leading underscore signals "internal"; @property gives validated attribute-style access.
- 05Dunder methods (__str__, __eq__, __len__…) let your objects use built-in Python syntax.
