ShareYourGroupShareYourGroupPython

Lesson 21 of 21 · about 8 minutes with the exercises

Classes and objects

Everything you have used in Python is an object. A string is an object with methods such as upper. A list is an object with methods such as append. A class is the pattern from which objects are made. str and list are classes that come with Python. In this lesson you write a class of your own.

You can write useful programs for a long time without creating classes. But you need to read them, because libraries are full of them, and the idea is simpler than its vocabulary suggests.

Why classes?

Suppose a program keeps data about bank accounts: a holder's name and a balance. It also has actions that go with that data: deposit, withdraw, show. A class lets you keep the data and the actions together in one place, under one name.

A first class

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

asha = Student("Asha", 78)
ravi = Student("Ravi", 91)
print(asha.name, asha.marks)
print(ravi.name, ravi.marks)

Output

Asha 78
Ravi 91

Going through it:

asha and ravi are two separate objects made from the same pattern. Each has its own name and marks. These stored values are called attributes, and you read them with a dot.

Adding methods

A method is a function defined inside a class. Its first parameter is always self, which gives it access to the object's attributes.

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

    def has_passed(self):
        return self.marks >= 33

    def describe(self):
        result = "passed" if self.has_passed() else "failed"
        return f"{self.name} scored {self.marks} and {result}."

s = Student("Meena", 28)
print(s.has_passed())
print(s.describe())

Output

False
Meena scored 28 and failed.

When you write s.describe(), Python passes s as self for you. That is why the call has empty brackets although the method has one parameter. A method can call another method of the same object through self.

Methods that change the object

class Account:
    def __init__(self, holder, balance=0):
        self.holder = holder
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Not enough balance.")
            return
        self.balance -= amount

acc = Account("Ravi", 500)
acc.deposit(1000)
acc.withdraw(2000)
acc.withdraw(300)
print(acc.holder, acc.balance)

Output

Not enough balance.
Ravi 1200

The balance lives inside the object and the rules for changing it live in the methods. The rest of the program does not need to know how withdrawing is checked. It just asks the account to do it.

Printing an object nicely

Printing an object of your own class shows something unhelpful by default. Define the special method __str__ to say what print should show.

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def __str__(self):
        return f"{self.title} ({self.pages} pages)"

b = Book("Malgudi Days", 264)
print(b)

Output

Malgudi Days (264 pages)

Many objects in a list

Objects go into lists like any other value. This is where classes start to pay off.

class Item:
    def __init__(self, name, price, qty):
        self.name = name
        self.price = price
        self.qty = qty

    def total(self):
        return self.price * self.qty

cart = [Item("Pen", 10, 5), Item("Notebook", 45, 3), Item("Bag", 600, 1)]
for item in cart:
    print(f"{item.name:<10}{item.total():>6}")
print("Grand total:", sum(item.total() for item in cart))

Output

Pen           50
Notebook     135
Bag          600
Grand total: 785

Inheritance in one example

A class can be built on top of another. The new class gets everything the old one has and can add to it or change it. Put the parent class in brackets.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

class Dog(Animal):
    def speak(self):
        return f"{self.name} says woof."

print(Animal("Cow").speak())
print(Dog("Sheru").speak())

Output

Cow makes a sound.
Sheru says woof.

Dog did not define __init__, so it uses the one from Animal. It did define its own speak, which replaces the parent's. This is enough inheritance for a first course.

The words, in one table

WordMeaning
classthe pattern, such as Student
object or instanceone thing made from the pattern, such as asha
attributea value stored in an object, such as asha.marks
methoda function that belongs to a class, such as describe
selfthe object a method is working on
__init__the method that sets up a new object

Class or dictionary?

For a simple record with a few fields and no behaviour, a dictionary is quicker to write and perfectly good. Reach for a class when the same data keeps travelling with the same functions, or when you find yourself passing the same three values into function after function.

Common mistakes

Try it yourself

Exercise 1. Write a class Rectangle with a length and a width, and a method area. Print the area of a 12 by 5 rectangle.

Show one answer
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

print(Rectangle(12, 5).area())

Output

60

Exercise 2. Write a class Counter that starts at 0 and has a method click that adds 1. Click it three times and print the count.

Show one answer
class Counter:
    def __init__(self):
        self.count = 0

    def click(self):
        self.count += 1

c = Counter()
c.click()
c.click()
c.click()
print(c.count)

Output

3

Exercise 3. Add a method grade to a Student class that returns "A" for 75 marks and above, "B" for 50 and above, and "C" otherwise. Test with 82.

Show one answer
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def grade(self):
        if self.marks >= 75:
            return "A"
        if self.marks >= 50:
            return "B"
        return "C"

print(Student("Asha", 82).grade())

Output

A

Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.