Tutorials Python Python Classes & Objects
Ch 32 / 58
Python Intermediate 13 min read Chapter 32 of 58

Python Classes & Objects

Object-Oriented Programming (OOP) is the paradigm that organises code around objects — self-contained bundles of data (attributes) and behaviour (methods). A class is the blueprint; an object (instance) is the concrete thing created from that blueprint. This chapter covers Python's complete class syntax: the class keyword, the __init__ constructor, the self parameter, instance vs class attributes, all method types, dunder methods, and real-world OOP design patterns used in professional Python code.

What you'll learn in this chapter
Defining a class — class keyword and anatomy
__init__ constructor and self parameter
Instance attributes vs class attributes
Instance, class and static methods
Dunder methods — __str__, __repr__, __len__
Real-world class design patterns
Advertisement

Object-Oriented Programming — Core Concepts

OOP is built on four pillars. This chapter covers the foundational two — Encapsulation (bundling data + behaviour) and Abstraction (hiding internal details). Chapters 33 & 34 cover Inheritance and Polymorphism.

Encapsulation
Bundle data + methods inside a class. Control access to internals.
Abstraction
Expose what's necessary. Hide implementation complexity.
Inheritance
Child class inherits attributes and methods from parent class.
Polymorphism
Same interface, different behaviour across different classes.
Class vs Object — the key distinction A class is the template/blueprint — defined once, describes structure and behaviour. An object (instance) is a concrete entity created from the class. You can create thousands of objects from a single class, each with its own data.

Defining a Class — Syntax & Anatomy

A class is defined with the class keyword, followed by the class name (CamelCase by convention), a colon, and an indented body. The simplest class can be just a pass statement.

Class Anatomy — BankAccount
class BankAccount :
Class Attributes (shared by all instances)
A
bank_name = "K2 Bank" str
A
interest_rate = 0.035 float
Instance Attributes (unique per object — set in __init__)
A
self.owner str
A
self.balance float
Methods
M
__init__(self, owner, balance) constructor
M
deposit(self, amount) instance
M
withdraw(self, amount) instance
M
__str__(self) dunder
Python — defining_class.py
# Simplest class — just a namespace
class Dog:
    pass

# Create objects (instances) from the class
rex  = Dog()    # calling the class creates an instance
fido = Dog()
print(type(rex))             # <class '__main__.Dog'>
print(isinstance(rex, Dog))   # True
print(rex is fido)           # False — different objects

# Class with a docstring
class Car:
    """Represents a car with make, model and year."""
    wheels = 4          # class attribute — shared by all Cars

__init__ Constructor & self

The __init__ method is the constructor — Python calls it automatically whenever you create a new object. The first parameter, self, refers to the newly created instance. You use self.attribute = value inside __init__ to set the object's own data.

Python — init_and_self.py
class Student:
    """Represents a student with a name and grade."""

    def __init__(self, name, grade, age=18):
        # self = the new object being created
        self.name  = name      # instance attribute
        self.grade = grade
        self.age   = age
        self._scores = []       # 'private' by convention (underscore)

# Creating objects — __init__ is called automatically
alice = Student("Alice", "A")         # age defaults to 18
bob   = Student("Bob",   "B", age=20)  # keyword arg

# Access instance attributes
print(alice.name)     # Alice
print(alice.grade)    # A
print(bob.age)        # 20

# Each object has its OWN copy of instance attributes
alice.name = "Alicia"              # only changes alice's name
print(alice.name)     # Alicia
print(bob.name)       # Bob — unchanged

# self is not a keyword — any name works, but self is universal convention
# def __init__(this, name): this.name = name  ← works but don't do this
What self really is self is not a magic keyword — it's just the conventional name for the first parameter of any instance method. Python automatically passes the calling object as the first argument. When you call alice.greet(), Python translates it to Student.greet(alice).
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Instance Attributes vs Class Attributes

Instance attributes are unique to each object — each instance has its own copy. Class attributes are shared across all instances. Understanding the difference prevents subtle bugs where one object's data unexpectedly affects others.

Python — class_vs_instance_attrs.py
class Employee:
    # Class attributes — shared by ALL instances
    company        = "K2infocom"
    employee_count = 0

    def __init__(self, name, salary):
        # Instance attributes — unique to this object
        self.name   = name
        self.salary = salary
        Employee.employee_count += 1  # update class attribute

e1 = Employee("Alice", 50000)
e2 = Employee("Bob",   60000)

# Class attribute — same for all instances
print(e1.company)              # K2infocom
print(e2.company)              # K2infocom
print(Employee.company)        # K2infocom — via class
print(Employee.employee_count) # 2

# Instance attribute — unique per object
print(e1.name, e1.salary)      # Alice 50000
print(e2.name, e2.salary)      # Bob   60000

# ⚠️ Mutable class attributes — the shared list trap
class BadTeam:
    members = []               # ← shared list!

    def add(self, name):
        self.members.append(name) # mutates the shared list

t1, t2 = BadTeam(), BadTeam()
t1.add("Alice")
print(t2.members)              # ['Alice'] ← t2 also affected! BUG

# ✅ Fix: use None default and create list in __init__
class GoodTeam:
    def __init__(self):
        self.members = []          # each instance gets its own list
Feature Instance Attribute Class Attribute
Defined in __init__ with self.x = ... Class body, outside methods
Scope Belongs to one specific instance Shared by all instances
Access via obj.attr obj.attr or ClassName.attr
Use for Per-object data (name, balance) Shared state (count, constants)

Method Types — Instance, Class & Static

Python supports three method types in a class. Instance methods (most common) receive self. Class methods receive cls (the class itself) and are used for alternative constructors. Static methods receive neither — they're utility functions logically grouped in the class.

Python — method_types.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    # ── Instance method — operates on self ───────────────
    def to_fahrenheit(self):
        return self.celsius * 9/5 + 32

    def to_kelvin(self):
        return self.celsius + 273.15

    def is_boiling(self):
        return self.celsius >= 100

    # ── Class method — alternative constructor pattern ────
    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        """Create Temperature from Fahrenheit value."""
        celsius = (fahrenheit - 32) * 5/9
        return cls(celsius)         # cls = Temperature

    @classmethod
    def from_kelvin(cls, kelvin):
        return cls(kelvin - 273.15)

    # ── Static method — utility, no self or cls ───────────
    @staticmethod
    def celsius_to_fahrenheit(c):
        """Standalone utility — no instance needed."""
        return c * 9/5 + 32

# ── Using all three ───────────────────────────────────
t1 = Temperature(100)
print(t1.to_fahrenheit())     # 212.0  — instance method
print(t1.is_boiling())        # True

t2 = Temperature.from_fahrenheit(212)   # class method
print(t2.celsius)             # 100.0

print(Temperature.celsius_to_fahrenheit(0))  # 32.0 — static

Dunder (Magic) Methods

Dunder methods (double underscore: __method__) are special methods Python calls automatically for specific operations — printing, comparison, arithmetic, iteration, and more. They let your custom objects behave like built-in types.

Python — dunder_methods.py
class Vector:
    """2D vector with operator overloading."""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    # __str__ — human-readable string (print())
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

    # __repr__ — unambiguous string (for debugging)
    def __repr__(self):
        return f"Vector(x={self.x!r}, y={self.y!r})"

    # __add__ — enables v1 + v2
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    # __sub__ — enables v1 - v2
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    # __mul__ — enables v * scalar
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    # __len__ — enables len(v)
    def __len__(self):
        return int((self.x**2 + self.y**2)**0.5)

    # __eq__ — enables v1 == v2
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    # __bool__ — enables if v:
    def __bool__(self):
        return self.x != 0 or self.y != 0

# ── Using the class ───────────────────────────────────
v1 = Vector(3, 4)
v2 = Vector(1, 2)

print(v1)              # Vector(3, 4)  — calls __str__
print(repr(v1))        # Vector(x=3, y=4) — calls __repr__
print(v1 + v2)         # Vector(4, 6)  — calls __add__
print(v1 - v2)         # Vector(2, 2)
print(v1 * 3)          # Vector(9, 12)
print(len(v1))         # 5  — magnitude (3-4-5 triangle)
print(v1 == Vector(3,4)) # True
Dunder Method Triggered by Purpose
__init__ MyClass() Constructor — initialise instance
__str__ str(obj), print(obj) Human-readable string
__repr__ repr(obj) Developer/debug string
__len__ len(obj) Return length/size
__add__ obj + other Addition operator
__eq__ obj == other Equality comparison
__lt__ obj < other Less-than comparison
__bool__ if obj: Truthiness
__iter__ for x in obj: Make iterable
__del__ Object destroyed Destructor / cleanup

Real-World Class Design

Here is a complete, professional class example — a BankAccount class with encapsulated balance, validation, and meaningful dunder methods. This pattern is used in Django models, API serialisers, and data layer objects.

Python — bank_account_class.py
class BankAccount:
    """A bank account with deposit, withdrawal and history."""

    bank_name     = "K2 Bank"       # class attribute
    interest_rate = 0.035

    def __init__(self, owner: str, initial_balance: float = 0.0):
        if initial_balance < 0:
            raise ValueError("Initial balance cannot be negative")
        self.owner    = owner
        self._balance = initial_balance   # _ = "private" by convention
        self._history = []

    # Property — read-only access to _balance
    @property
    def balance(self):
        return self._balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Deposit amount must be positive")
        self._balance += amount
        self._history.append(f"+{amount:.2f}")

    def withdraw(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Withdrawal must be positive")
        if amount > self._balance:
            raise ValueError("Insufficient funds")
        self._balance -= amount
        self._history.append(f"-{amount:.2f}")

    def add_interest(self) -> None:
        self.deposit(self._balance * BankAccount.interest_rate)

    @classmethod
    def from_savings_plan(cls, owner, monthly, months):
        """Alternative constructor — open account with saved amount."""
        return cls(owner, monthly * months)

    def __str__(self):
        return f"{BankAccount.bank_name}: {self.owner}'s account — ₹{self._balance:,.2f}"

    def __repr__(self):
        return f"BankAccount(owner={self.owner!r}, balance={self._balance})"

# ── Using the class ───────────────────────────────────
acc = BankAccount("Alice", 10000)
acc.deposit(5000)
acc.withdraw(2000)
acc.add_interest()
print(acc)                         # human-readable
print(acc.balance)                 # read-only property
print(acc._history)

sav = BankAccount.from_savings_plan("Bob", 5000, 12)
print(sav)                         # Bob saved ₹60,000

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all class and OOP examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every class example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • A class is a blueprint; an object (instance) is a concrete entity created from it. OOP's four pillars: Encapsulation, Abstraction, Inheritance, Polymorphism.
  • Define a class with class ClassName: (CamelCase convention). Create objects with obj = ClassName().
  • __init__ is the constructor — called automatically when an object is created. Use self.attr = value to set instance attributes.
  • self is not a keyword — it's the first parameter of every instance method, receiving the calling object automatically.
  • Instance attributes: unique per object, set in __init__. Class attributes: shared by all instances, defined in the class body.
  • Instance methods receive self. Class methods (@classmethod) receive cls — used for alternative constructors. Static methods (@staticmethod) receive neither — utility functions grouped in the class.
  • Dunder methods (__str__, __repr__, __add__, __eq__, etc.) let custom objects behave like built-in types.
  • Use single underscore _attr for "private" convention; use @property for controlled attribute access.
  • Always validate inputs in __init__, raise ValueError for invalid data, and implement __str__ for readable output.
⚡
Free Resource
Download our Python Classes & Objects Cheat Sheet
Class syntax, __init__, self, attributes, method types, dunder methods & OOP patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

__init__ is the constructor — a special method automatically called by Python when you create a new instance with ClassName(args). Its primary purpose is to initialise the instance's attributes.

Inside __init__, you use self.attribute = value to attach data to the new object. It can accept any number of parameters (after self) which are passed in from the object-creation call.

class Car:
    def __init__(self, make, year):
        self.make = make   # called when: Car("Toyota", 2025)
        self.year = year
✓ Answer

Instance attributes are defined with self.attr = value inside methods (usually __init__). Each instance has its own independent copy — changing one object's instance attribute does not affect others.

Class attributes are defined in the class body outside methods. They are shared across all instances. Modifying a class attribute via the class name changes it for all instances. Be careful with mutable class attributes (lists, dicts) — all instances share the same object.

✓ Answer

@classmethod takes cls (the class itself) as its first argument. It can access and modify class-level state, and is typically used as an alternative constructor (factory method) to create instances in different ways.

@staticmethod takes neither self nor cls. It's a plain function that is logically related to the class but doesn't need access to the instance or class. Used for utility/helper functions grouped with the class.

✓ Answer

__str__ returns a human-readable string — used by print() and str(). It should be easy to read and understand.

__repr__ returns an unambiguous developer/debug string — used in the REPL and by repr(). Ideally it should look like a constructor call that can recreate the object.

If only __repr__ is defined, Python uses it for both print() and the REPL. If only __str__ is defined, the REPL falls back to the default __repr__.

✓ Answer

Python instance methods need to know which specific object they are operating on. When you call alice.greet(), Python needs to know it's Alice's data that the method should work with, not Bob's or anyone else's.

Python passes self automatically by translating the call: alice.greet() becomes Student.greet(alice) internally. The name self is just a convention — you could name it anything, but self is the universal Python standard.

MCQ 1 of 3
Which method is automatically called when a new object is created from a class?
MCQ 2 of 3
Which decorator creates a method that receives the class as its first argument instead of an instance?
MCQ 3 of 3
What dunder method is called by print(obj)?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel