Skip to main content
Albero Academy

Object-Oriented Programming

Model your problem with classes and objects — attributes, methods, __init__, inheritance, encapsulation and the dunder methods.

Chapter 13Python20 min readBeginner friendly
  • #Python
  • #OOP
  • #Classes

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:

a first class
class Student:
pass
a = Student() # an instance
b = Student() # a different instance
print(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:

constructor & attributes
class Student:
def __init__(self, name, programme):
self.name = name # instance attributes
self.programme = programme
self.placed = False
aanya = Student("Aanya", "Data Analytics")
print(aanya.name) # Aanya
aanya.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:

behaviour lives with the data
class Student:
def __init__(self, name, package=0):
self.name = name
self.package = package
def give_raise(self, pct):
self.package *= 1 + pct / 100
def 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:

inherit & override
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi, I'm {self.name}"
class Student(Person): # Student IS-A Person
def __init__(self, name, programme):
super().__init__(name) # run Person's __init__
self.programme = programme
def greet(self): # override
return 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:

properties
class Account:
def __init__(self, balance=0):
self._balance = balance
@property
def balance(self): # read like an attribute: acc.balance
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance can't be negative")
self._balance = value
acc = 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:

DunderEnables
__init__Construction: Student(...)
__str__str(obj) / print(obj)
__repr__The debug representation
__eq__obj1 == obj2
__len__len(obj)
make objects Pythonic
class Batch:
def __init__(self, students):
self.students = students
def __len__(self):
return len(self.students)
def __str__(self):
return f"Batch of {len(self)}"
b = Batch(["Aanya", "Rohan"])
print(len(b)) # 2
print(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

  1. 01A class bundles related data (attributes) and behaviour (methods) into one type.
  2. 02__init__ is the constructor; self is the current instance every method receives first.
  3. 03Inheritance reuses and specialises a class; super() calls the parent version.
  4. 04A leading underscore signals "internal"; @property gives validated attribute-style access.
  5. 05Dunder methods (__str__, __eq__, __len__…) let your objects use built-in Python syntax.