Chapter 46 of 54

Classes & Objects in Python

So far, you've stored data in variables, lists and dictionaries, and written functions that work on that data. As programs grow, keeping related data and functions together becomes important. A student has a name, a roll number and marks, and things a student can do, like introducing themselves or calculating a grade.

Object-Oriented Programming (OOP) lets you bundle data and behaviour into one unit called an object. In Python, everything is already an object: strings, lists and even functions. In this chapter, you'll learn to create your own types using classes.

Class vs Object

A class is a blueprint that describes what data and behaviour something should have. An object (or instance) is an actual thing built from that blueprint.

Think of a house plan and real houses:

      Class: Student  (blueprint)
      - name, roll       <- data (attributes)
      - introduce()      <- behaviour (methods)
             |
     -----------------
     |               |
 Object: asha    Object: ravi
 name = "Asha"   name = "Ravi"
 roll = 101      roll = 102

One class, many objects. Every object has the same structure but its own values. You have already used this idea: list is a class, and every list you create is an object of that class.


Creating a Class

Use the class keyword. By convention, class names use PascalCase (each word capitalised).

class Student:
    pass

s1 = Student()
s2 = Student()

print(type(s1))
print(s1 is s2)

Output:

<class '__main__.Student'>
False

Calling the class like a function, Student(), creates a new object. s1 and s2 are two separate objects. (__main__ simply means the class was defined in the file you ran directly.)


The __init__ Method and self

An empty class is not very useful. We want every student to start with a name and a roll number. That's the job of __init__:

class Student:
    def __init__(self, name, roll):
        self.name = name
        self.roll = roll

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

asha = Student("Asha", 101)
ravi = Student("Ravi", 102)

asha.introduce()
ravi.introduce()

Output:

Hi, I am Asha, roll number 101
Hi, I am Ravi, roll number 102

What happens step by step

  1. Student("Asha", 101) creates a new, empty object.

  2. Python automatically calls __init__(new_object, "Asha", 101).

  3. Inside __init__, self is that new object, so self.name = name stores "Asha" on it.

  4. The finished object is assigned to asha.

__init__ is often called the constructor. (Strictly, it initialises an object that Python has already created, but "constructor" is the common word in interviews.)

What is self?

self is a reference to the object the method is working on. When you write asha.introduce(), Python actually calls:

Student.introduce(asha)

So inside introduce, self is asha, and self.name is "Asha". That is how one method works correctly for every object. self is not a keyword, only a strong convention, but always use the name self.


Attributes and Methods

  • Attributes are variables that belong to an object, like asha.name.

  • Methods are functions defined inside a class, like asha.introduce(). The first parameter is always self.

You can read and change attributes with dot notation:

print(asha.name)
asha.name = "Asha Rao"
asha.introduce()

Output:

Asha
Hi, I am Asha Rao, roll number 101

Changing asha.name does not affect ravi. Each object keeps its own data.


Instance Attributes vs Class Attributes

Attributes set on self belong to one object. Attributes written directly inside the class body belong to the class and are shared by all objects.

class Student:
    college = "ABC Institute"   # class attribute (shared)
    count = 0                   # class attribute (shared)

    def __init__(self, name):
        self.name = name        # instance attribute (per object)
        Student.count += 1

a = Student("Asha")
b = Student("Ravi")

print(a.college, b.college)
print(Student.count)

Student.college = "XYZ University"
print(a.college, b.college)

Output:

ABC Institute ABC Institute
2
XYZ University XYZ University

When you read a.college, Python first looks in the object. If it is not found there, it looks in the class. Be careful: assigning through an object creates a new instance attribute that hides the class one:

a.college = "Changed"
print(a.college, b.college, Student.college)
print(a.__dict__)

Output:

Changed XYZ University XYZ University
{'name': 'Asha', 'college': 'Changed'}

__dict__ shows the attributes stored on the object itself.

Instance attributeClass attribute
DefinedInside methods, on selfDirectly in the class body
Belongs toOne objectThe class (shared)
Exampleself.namecollege, count
Use forData that differs per objectConstants, counters, defaults

A Complete Example: Bank Account

Methods can change an object's state and validate data:

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.balance += amount
        print(f"Deposited {amount}. Balance: {self.balance}")

    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Insufficient balance. Balance: {self.balance}")
            return
        self.balance -= amount
        print(f"Withdrew {amount}. Balance: {self.balance}")

acc = BankAccount("Meera", 1000)
acc.deposit(500)
acc.withdraw(2000)
acc.withdraw(300)

other = BankAccount("Kiran")
print(other.balance)

Output:

Deposited 500. Balance: 1500
Insufficient balance. Balance: 1500
Withdrew 300. Balance: 1200
0

__init__ can have default parameter values just like normal functions, so BankAccount("Kiran") starts with a balance of 0.

If you print the object itself, you get a not-very-helpful default:

print(acc)

Output (the address will differ on your machine):

<__main__.BankAccount object at 0x00000276312A8AD0>

You'll learn how to give objects a readable printed form with __str__ in the Polymorphism & Dunder Methods chapter.


Class Methods and Static Methods

Besides normal (instance) methods, a class can have two other kinds:

class Circle:
    pi = 3.14159

    def __init__(self, radius):
        self.radius = radius

    def area(self):                 # instance method: gets self
        return round(Circle.pi * self.radius ** 2, 2)

    @classmethod
    def from_diameter(cls, d):      # class method: gets the class
        return cls(d / 2)

    @staticmethod
    def is_valid_radius(r):         # static method: gets neither
        return r > 0

c = Circle.from_diameter(10)
print(c.radius, c.area())
print(Circle.is_valid_radius(-3))

Output:

5.0 78.54
False
TypeFirst parameterTypical use
Instance methodself (the object)Work with one object's data
@classmethodcls (the class)Alternative ways to create objects
@staticmethodNoneHelper function that logically belongs to the class

The @ lines are called decorators. You'll learn how they work in a later chapter; for now, just know they change how the method is called.


Common Mistakes

1. Forgetting self in a method

class Demo:
    def hello():
        print("hi")

Demo().hello()

This raises:

TypeError: Demo.hello() takes 0 positional arguments but 1 was given

Python passes the object automatically, so the method must accept self.

2. Forgetting self. when storing data

Writing name = name inside __init__ only creates a local variable that disappears when the method ends. You need self.name = name.

3. Using a mutable class attribute for per-object data

class Team:
    members = []          # shared by ALL teams!

    def add(self, name):
        self.members.append(name)

t1 = Team()
t2 = Team()
t1.add("Asha")
print(t2.members)

Output:

['Asha']

t2 was never touched, yet it has Asha. The list lives on the class, so both objects share it. The fix is to create the list in __init__ with self.members = [], so each object gets its own.

4. Misspelling __init__

It needs two underscores on each side. _init_ or __int__ will not be called when the object is created. (__int__ is actually a different special method, used by int().)


Summary

  • A class is a blueprint; an object is an instance created from it with ClassName().

  • __init__ runs automatically when an object is created and sets up its attributes.

  • self refers to the current object; every instance method takes it as the first parameter.

  • Instance attributes belong to one object; class attributes are shared by all.

  • @classmethod receives the class, @staticmethod receives nothing extra.

A class bundles data (attributes) and behaviour (methods) together; each object carries its own copy of the data.

Interview tip: Be ready to explain the four pillars of OOP: encapsulation, abstraction, inheritance and polymorphism. The next few chapters cover them, starting with inheritance; abstraction appears in the Polymorphism & Dunder Methods chapter.

Practice: Create a Rectangle class with length and width, and methods area() and perimeter(). Then create a Library class that stores a list of books and has methods to add, remove and display books.