Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

4.2 Instance Versus Class Attributes

How it works

An attribute set on the class is shared by every instance; one set in the initialiser belongs to that instance alone.

Put per-object data in the initialiser and shared constants on the class.

Common error

A mutable class attribute being modified through one instance and appearing changed for all of them.

Worked example

Python

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

a = Bag()
b = Bag()
a.items.append("book")
print(a.items)
print(b.items)

Output

['book']
[]

Creating the list inside __init__ gives each instance a separate list. A mutable class-level list would be shared unless replaced on an instance.

Exercises

4.2.1 · Trace

Determine the exact output and explain the state changes.

Python

class Item:
    category = "tool"

a = Item()
b = Item()
a.category = "book"
print(a.category, b.category)
Show solution

Output

book tool

The instance assignment shadows the class attribute for a only.

4.2.2 · Explain

Why can items = [] in the class body cause unexpected sharing between instances?

Show solution

The list is stored on the class and may be reached by multiple instances. Mutating it does not create an independent list for each instance.

Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic