Skip to content

Module 11 · Object-Oriented Programming — topic 10 of 25

Class variables

Variables shared by all instances of a class: constants, counters and defaults, reading them through instances or the class, and the trap of modifying them through self.

Beginner 8 min read·Lesson 167 of 306 in Python Programming

Learning objectives

  • Define and use class variables
  • Update shared state correctly through the class
  • Avoid shadowing class variables by assigning through self

Definition

A class variable is defined directly in the class body. It belongs to the class object and is shared by all instances; reading obj.name finds it if the instance has no attribute of that name.

Introduction

Some data belongs to the concept, not to individual objects: the interest rate for all savings accounts, or how many students have been created. That data goes in class variables.

Why it matters

Class variables avoid repeating the same value in every object and give one place to change shared configuration — but writing to them through self is a classic bug.

Detailed explanation

Variables in the class body (outside methods) are class variables: rate = 0.04.

They can be read as ClassName.rate or self.rate; the instance lookup falls back to the class.

To change the shared value, assign through the class: SavingsAccount.rate = 0.05 or type(self).rate = ....

Assigning self.rate = ... creates an instance variable that shadows the class variable for that object only.

Typical uses: constants (MAX_SIZE), counters of created objects, default settings and lookup tables.

Mutable class variables (lists, dicts) are shared by every instance — usually unintended unless it really is a shared registry.

Syntax

Python
class Student:
school = "KENHOLT" # shared value
count = 0 # shared counter
def __init__(self, name):
self.name = name
Student.count += 1 # update via the class
  • Defined in the class body.
  • Read via class or instance.
  • Write via the class.

Code examples

Shared values and counters

Python
class Student:
school = "KENHOLT"
count = 0
def __init__(self, name):
self.name = name
Student.count += 1
a, b = Student("Asha"), Student("Ravi")
print(a.school, b.school, Student.count)
Output
KENHOLT KENHOLT 2

Changing the shared value

Python
class Account:
rate = 0.04
a, b = Account(), Account()
Account.rate = 0.05
print(a.rate, b.rate)
Output
0.05 0.05

More examples

The self-assignment trap

Python
class Ticket:
sold = 0
def __init__(self, event):
self.event = event
self.number = Ticket.sold + 1
Ticket.sold += 1 # correct: update the class
class BuggyTicket:
sold = 0
def __init__(self, event):
self.sold += 1 # creates an instance attribute instead
self.number = self.sold
t = [Ticket("concert") for _ in range(3)]
print([x.number for x in t], Ticket.sold)
b = [BuggyTicket("concert") for _ in range(3)]
print([x.number for x in b], BuggyTicket.sold)
Output
[1, 2, 3] 3
[1, 1, 1] 0

Step-by-step explanation

  • Ticket updates the counter through the class, so each new ticket sees the incremented value.
  • In BuggyTicket, self.sold += 1 reads the class value 0, adds 1 and stores the result on the instance.
  • Every buggy ticket therefore gets number 1, and the class counter never changes.

Expected output

Running “The self-assignment trap” prints exactly:

TextOutput
[1, 2, 3] 3
[1, 1, 1] 0

Practical applications

  • Configuration defaults on base classes in frameworks.
  • Registries of plugins or subclasses.

Best practices

  • Use class variables for constants and genuinely shared data.
  • Name constants in UPPER_CASE.
  • Modify shared values through the class name.

Common mistakes

Incrementing via self

Avoid

self.count += 1

Prefer

type(self).count += 1 # or ClassName.count += 1

Assignment through self creates an instance attribute.

Shared mutable list

Avoid

class Group:
members = []

Prefer

class Group:
def __init__(self):
self.members = []

One list would be shared by every group.

Important notes

  • type(self).count is preferred over the class name when subclasses should have their own counters.

Key takeaways

  • Class variables are shared by all instances.
  • Read them through the instance or the class.
  • Write through the class, not self.

Try it yourself

  1. 1
    Give an Order class an auto-incrementing order number using a class variable.
  2. 2
    Store a tax rate as a class variable and show how changing it affects all products.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic