IntermediateLesson 14 of 306 min read

Classes and objects: your own types

Create blueprints for objects with classes: constructors, methods, special methods, properties and class attributes.

In this lesson you will

  • Write a class with __init__ and methods
  • Understand self and attributes
  • Use special methods like __str__ and __add__
  • Add rules with @property

About 22 minutes

Blueprints for your own kinds of thing

Think of a builder with one blueprint who can construct twenty houses. Each house has its own address and colour, but the same structure. In Python, a class is a blueprint, and each thing built from it is an object (or instance). You have used objects all along: a string, a list and a dictionary are all objects of built-in classes. Now you will make your own, such as a Student, a Product or a BankAccount.

Why classes?

Suppose a program tracks students. Without classes, you juggle separate lists: names, ages, marks, and hope they stay in step. A class bundles the data (name, marks) and the actions (calculate average, add a mark) of one student into one tidy unit.

Your first class

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

    def birthday(self):
        self.age += 1

rex = Dog("Rex", 3)
bella = Dog("Bella", 5)

print(rex.name, rex.age)
print(rex.bark())
rex.birthday()
print(rex.age)
print(bella.bark())
Rex 3
Rex says woof!
4
Bella says woof!
  • class Dog: declares the blueprint. Class names use CapitalWords.
  • __init__ is the constructor. Python calls it automatically when you write Dog("Rex", 3). It sets up the new object’s data.
  • self means “this particular object”. It is always the first parameter of a method, and Python fills it in for you.
  • self.name = name stores data on the object. These stored values are called attributes.
  • Functions inside a class are called methods.
Good to know

When you call rex.bark(), Python quietly passes rex as self. That is how the method knows whose name to use. Each object keeps its own separate data.

Objects keep their own data

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

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

a = Counter()
b = Counter()
a.increase()
a.increase()
b.increase()
print(a.count, b.count)
2 1

A realistic example: a bank account

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

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Not enough money")
        self.balance -= amount

    def summary(self):
        return f"{self.owner}: Rs {self.balance:,.2f}"

acc = BankAccount("Sara", 1000)
acc.deposit(500)
acc.withdraw(200)
print(acc.summary())

try:
    acc.withdraw(5000)
except ValueError as e:
    print("Refused:", e)
Sara: Rs 1,300.00
Refused: Not enough money

This is the great gain of classes: the rules (no negative deposits, no overdrafts) live next to the data they protect. Any code that uses the account must go through those methods.

Special methods: making objects behave naturally

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

    def __repr__(self):                 # how the object is shown in the shell and lists
        return f"Point({self.x}, {self.y})"

    def __str__(self):                  # how print() shows it
        return f"({self.x}, {self.y})"

    def __add__(self, other):           # makes + work
        return Point(self.x + other.x, self.y + other.y)

    def __eq__(self, other):            # makes == work
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1)
print([p1, p2])
print(p1 + p2)
print(p1 == Point(1, 2))
(1, 2)
[Point(1, 2), Point(3, 4)]
(4, 6)
True

Methods with double underscores on both sides are called special or dunder methods. They let your objects work with Python’s own features: print, +, ==, len(), sorting and more. Without __str__, printing an object shows an unhelpful memory address.

class Plain:
    pass

print(Plain())     # not helpful
<__main__.Plain object at 0x7fae220af230>

Class attributes and static helpers

class Circle:
    PI = 3.14159                         # class attribute: shared by all circles

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

    def area(self):
        return Circle.PI * self.radius ** 2

    @classmethod
    def from_diameter(cls, d):           # an alternative constructor
        return cls(d / 2)

    @staticmethod
    def is_valid_radius(r):              # a helper that needs no object
        return r > 0

c = Circle.from_diameter(10)
print(c.radius, round(c.area(), 2))
print(Circle.is_valid_radius(-3))
5.0 78.54
False

Properties: attributes with rules

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def fahrenheit(self):                # read like an attribute
        return self.celsius * 9 / 5 + 32

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):            # runs on every assignment
        if value < -273.15:
            raise ValueError("Below absolute zero")
        self._celsius = value

t = Temperature(100)
print(t.fahrenheit)
t.celsius = 0
print(t.fahrenheit)
try:
    t.celsius = -300
except ValueError as e:
    print("Error:", e)
212.0
32.0
Error: Below absolute zero
Good to know

Python has no strict private attributes. By convention, a name starting with an underscore, such as _celsius, means “internal; please do not touch”.

When to use a class

  • You have several things of the same kind, each with its own data: students, products, game characters.
  • Some data and the functions that work on it belong together.
  • You want to protect rules (a balance can never go negative).
  • For a single set of related functions, a simple module is enough. You do not need a class for everything.
Common mistake

Forgetting self. Writing def bark(): inside a class and then calling rex.bark() fails with TypeError: bark() takes 0 positional arguments but 1 was given. Every ordinary method needs self as its first parameter, and inside the class you must write self.name, not just name.

Practice

Write a class Rectangle with width and height, and methods area() and perimeter(). Create one that is 4 by 5 and print both values.

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

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

    def perimeter(self):
        return 2 * (self.width + self.height)

r = Rectangle(4, 5)
print(r.area(), r.perimeter())
20 18
Practice

Write a Student class that stores a name and a list of marks, with an add_mark(mark) method and an average() method. Add three marks and print the average to one decimal.

Hint: Start with marks = [] in __init__.

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

    def add_mark(self, mark):
        self.marks.append(mark)

    def average(self):
        return sum(self.marks) / len(self.marks)

s = Student("Sara")
for m in (72, 91, 85):
    s.add_mark(m)
print(f"{s.name}: {s.average():.1f}")
Sara: 82.7
Start with a plain list of dictionaries

If your data is just records, a list of dictionaries is perfectly fine. Reach for a class when behaviour (rules and actions) joins the data.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is __init__?

  1. A loop
  2. A built-in function
  3. The constructor that sets up a new object
  4. A module

Python calls it when you create an object.

What does self refer to?

  1. The class itself
  2. The module
  3. A global variable
  4. The particular object the method was called on

self is the current instance.

What does __str__ control?

  1. The object’s type
  2. What print() shows for the object
  3. The object’s memory
  4. Sorting only

It defines the friendly text version.

What does @property do?

  1. Makes a class global
  2. Deletes an attribute
  3. Lets a method be used like an attribute
  4. Creates a loop

Properties look like attributes but run code.

What error appears if a method forgets self?

  1. TypeError about the number of arguments
  2. NameError
  3. KeyError
  4. None

Python passes the object as the first argument.

Summary

  • A class is a blueprint; objects are instances.
  • __init__ sets up data; self is the object.
  • Special methods plug objects into Python features.
  • @property adds rules to attributes.

Next lesson

Next: inheritance and dataclasses, building on classes you already have.

Questions

When should I use a class instead of a dictionary?

When the data needs behaviour or rules. For plain records, a dictionary or dataclass is simpler.

What is the difference between a function and a method?

A method is a function that belongs to a class and receives the object as self.

Do I always need __init__?

No. A class can have no constructor, but most useful classes use one.

Progress is saved in this browser.