Learn / Intermediate / Lesson 3

Classes and objects

14 min Tested on Python 3.15Updated By
In short

A class is a blueprint that bundles data (attributes) and behaviour (methods); each object made from it is an instance. You define one with class Name:, set up its data in __init__(self, ...), and reach that data through self. Classes are worth it when several functions keep working on the same piece of data.

Your first class

Python
class BankAccount:
    def __init__(self, owner: str, balance: float = 0) -> None:
        self.owner = owner
        self.balance = balance

    def deposit(self, amount: float) -> None:
        self.balance += amount

    def withdraw(self, amount: float) -> None:
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount


account = BankAccount("Asha", 100)
account.deposit(50)
account.withdraw(30)
print(account.owner, account.balance)
Output
Asha 120
  • __init__ runs automatically when you create an object: BankAccount("Asha", 100).
  • self is the object itself. self.balance is that account's own balance.
  • Methods are functions inside the class; Python passes self for you.
  • Class names use CapWords; methods and attributes use snake_case.

A readable print-out with __repr__

Python
class Point:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

    def __repr__(self) -> str:
        return f"Point(x={self.x}, y={self.y})"

    def distance_to_origin(self) -> float:
        return (self.x ** 2 + self.y ** 2) ** 0.5

p = Point(3, 4)
print(p)
print(p.distance_to_origin())
Output
Point(x=3, y=4)
5.0

Without __repr__, printing an object shows something like <__main__.Point object at 0x7f...>. Methods with double underscores are "dunder" methods: hooks Python calls for you.

Class attributes

Python
class Employee:
    company = "PythonMates"     # shared by all instances
    headcount = 0

    def __init__(self, name: str) -> None:
        self.name = name          # one per instance
        Employee.headcount += 1

a = Employee("Ana")
b = Employee("Ben")
print(a.company, b.company)
print(Employee.headcount)
Output
PythonMates PythonMates
2

Inheritance

Python
class Shape:
    def __init__(self, name: str) -> None:
        self.name = name

    def area(self) -> float:
        raise NotImplementedError

    def describe(self) -> str:
        return f"{self.name} with area {self.area():.1f}"


class Rectangle(Shape):
    def __init__(self, width: float, height: float) -> None:
        super().__init__("rectangle")
        self.width = width
        self.height = height

    def area(self) -> float:
        return self.width * self.height


class Circle(Shape):
    def __init__(self, radius: float) -> None:
        super().__init__("circle")
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2


for shape in [Rectangle(3, 4), Circle(1)]:
    print(shape.describe())
Output
rectangle with area 12.0
circle with area 3.1

A subclass reuses everything from its parent and overrides what's different. super().__init__(...) runs the parent's setup. Keep hierarchies shallow — one or two levels is plenty.

Properties: computed and protected attributes

Python
class Temperature:
    def __init__(self, celsius: float) -> None:
        self.celsius = celsius

    @property
    def fahrenheit(self) -> float:
        return self.celsius * 9 / 5 + 32

    @property
    def celsius(self) -> float:
        return self._celsius

    @celsius.setter
    def celsius(self, value: float) -> None:
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._celsius = value

t = Temperature(20)
print(t.fahrenheit)
t.celsius = 30
print(t.fahrenheit)
try:
    t.celsius = -300
except ValueError as err:
    print("Error:", err)
Output
68.0
86.0
Error: below absolute zero

Practice

Write a class Counter with a count attribute starting at 0, a method increment(step=1) that adds to it, and a __repr__ that returns Counter(count=N). Create one, increment it once by default and once by 5, then print it.

Expected output:
Counter(count=6)
Your code

Quick check

1. What is self?

2. What does super().__init__() do in a subclass?

3. Why add __repr__?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →