Intermediate Python · Lesson 9 of 14

Classes and objects

Create your own types with class, set up objects with __init__, add methods that use self, and tell class attributes from instance attributes.

About 18 minutes · code runs in your browser, nothing to install

A class is a blueprint for a new kind of value. Each value built from it is an object (also called an instance). Objects bundle data (attributes) with the functions that work on that data (methods). You already use objects all the time: every string is an object of class str, with methods like upper().

class statement defines a class. The special method __init__ runs when a new object is made and sets up its attributes. Its first parameter, self, is the object being built.

Pythoneditable
class Pet:
    def __init__(self, name, species, age):
        self.name = name
        self.species = species
        self.age = age

    def describe(self):
        return f"{self.name} is a {self.age}-year-old {self.species}"

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

rex = Pet("Rex", "dog", 3)
tom = Pet("Tom", "cat", 7)
print(rex.describe())
rex.have_birthday()
print(rex.age, tom.age)
Output
Rex is a 3-year-old dog
4 7

Each object keeps its own attributes: Rex's birthday does not change Tom.

When you call rex.describe(), Python passes rex in as self for you. That is why methods are defined with self but called without it.

A class with behaviour

Methods can check rules before changing an object, so the object always stays in a sensible state.

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

    def deposit(self, amount):
        if amount <= 0:
            print("Deposit must be positive")
            return
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Sorry {self.owner}, not enough money")
        else:
            self.balance -= amount

acct = BankAccount("Sofia", 100)
acct.deposit(50)
acct.withdraw(500)
acct.withdraw(30)
acct.deposit(-5)
print(acct.owner, acct.balance)
Output
Sorry Sofia, not enough money
Deposit must be positive
Sofia 120

Class attributes and instance attributes

An attribute set on self belongs to one object. An attribute written directly in the class body is shared by all objects of that class, which suits constants and counters.

Pythoneditable
class Ticket:
    price = 12.0
    sold = 0

    def __init__(self, film):
        self.film = film
        Ticket.sold += 1

a = Ticket("Space Garden")
b = Ticket("Night Train")
print(a.film, b.film)
print(a.price, b.price, Ticket.sold)
print(isinstance(a, Ticket))
Output
Space Garden Night Train
12.0 12.0 2
True

Computed attributes with @property

Put @property above a method and it is read like an attribute, without brackets. Use it for values that are calculated from other attributes, so they never get out of date.

Pythoneditable
class Basket:
    def __init__(self):
        self.items = []

    def add(self, name, price):
        self.items.append((name, price))

    @property
    def total(self):
        return round(sum(price for _, price in self.items), 2)

b = Basket()
b.add("Bread", 2.40)
b.add("Cheese", 6.15)
print(b.total)
print(len(b.items), "items")
Output
8.55
2 items
Watch out: print(rex) on an object without a __str__ method shows something like <__main__.Pet object at 0x...>, with a memory address that changes every run. Print attributes instead, or add __str__, as shown in Special methods and dataclasses.

✎ Exercise

Write a class Rectangle with width and height, a method area(), a method perimeter() and a property is_square.

Hint: Store both sizes on self in __init__. Every method takes self as its first parameter.

Your codewrite your answer, then Run
class Rectangle:
    # your code here
    pass

r = Rectangle(3, 4)
s = Rectangle(5, 5)
print(r.area(), r.perimeter(), r.is_square)
print(s.area(), s.perimeter(), s.is_square)

Expected output:

12 14 False
25 20 True
Show a solution
Solutioneditable
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)

    @property
    def is_square(self):
        return self.width == self.height

r = Rectangle(3, 4)
s = Rectangle(5, 5)
print(r.area(), r.perimeter(), r.is_square)
print(s.area(), s.perimeter(), s.is_square)
Output
12 14 False
25 20 True

Check yourself

1. What is self inside a method?

2. When does __init__ run?

3. An attribute written in the class body, outside any method, is…

Spotted a mistake on this page? Tell us