Python Class Attributes, Class Methods and Static Methods
What you will learn
- Class attributes: data shared by every object
- How Python looks up an attribute, and how an object can shadow a class attribute
- The
self.n += 1trap, and counting instances @classmethodand alternative constructors@staticmethodfor helper functions- How to choose between instance, class and static methods
1. Class attributes
In lesson 13.1, each object had its own attributes, created with self.x = ... in __init__. A variable written directly in the class body, outside any method, belongs to the class, and is shared by all its objects. It is a class attribute:
class Dog:
species = "Canis familiaris"
count = 0
def __init__(self, name):
self.name = name
Dog.count += 1
a = Dog("A")
b = Dog("B")
print(Dog.species, a.species, b.species)
print(Dog.count, a.count)
print(vars(a))
Canis familiaris Canis familiaris Canis familiaris
2 2
{'name': 'A'}
speciesandcountlive in the class.vars(a)shows onlyname.- You can reach a class attribute through the class (
Dog.species) or through any object (a.species). Dog.count += 1inside__init__changes the class attribute, so it counts every dog ever made.
Use class attributes for:
| Use | Example |
|---|---|
| constants shared by all objects | PI = 3.14159 |
| default values | species = "dog" |
| counters and registries | how many objects exist |
| settings that belong to the type, not to one object | max_speed = 120 |
Quick check: where is `species` stored: in each dog, or in the class?
In the class, once. Each dog finds it there.
2. How lookup works
When you write a.species, Python looks first in the object, then in the class, then in the parent classes (lesson 13.5). It uses the first place that has the name:
a.species = "changed"
print(a.species, b.species, Dog.species)
print(vars(a))
changed Canis familiaris Canis familiaris
{'name': 'A', 'species': 'changed'}
Assigning through an object never changes the class attribute. It creates a new attribute in that object, which then hides (shadows) the class one. Only a is affected: b and the class are not.
Dog.species = "new"
print(a.species, b.species, Dog.species)
del a.species
print(a.species)
changed new new
new
- Assigning through the class (
Dog.species = "new") changes it for every object that has not shadowed it. astill showschanged, because its own attribute takes priority.- After
del a.species, the shadow is gone, andasees the class value again.
To change shared data, always assign through the class name.
3. The += trap
This mistake is very common:
class Bad:
n = 0
def hit(self):
self.n += 1
b1 = Bad()
b2 = Bad()
b1.hit()
b1.hit()
print(b1.n, b2.n, Bad.n)
print(vars(b1))
2 0 0
{'n': 2}
The author wanted a shared counter. But self.n += 1 means self.n = self.n + 1. Python reads self.n (finding the class value 0), adds 1, and then assigns the result to self.n, which creates an instance attribute n on b1. The class attribute stays at 0. To change the shared counter, write Bad.n += 1 or type(self).n += 1.
Counting instances and giving ids
class IdGen:
_next = 1
def __init__(self):
self.id = IdGen._next
IdGen._next += 1
print([IdGen().id for _ in range(3)])
print(IdGen._next)
[1, 2, 3]
4
Each new object takes the next number, and bumps the shared counter. This is a typical, correct use of a class attribute.
Mutable class attributes are shared
A list or dictionary at class level is one object for everyone (lesson 13.2):
class Shared:
tags = []
def add(self, t):
self.tags.append(t)
x = Shared()
y = Shared()
x.add("a")
print(y.tags, Shared.tags)
['a'] ['a']
That is right only if you mean to share (a registry, a cache). Otherwise, create self.tags = [] in __init__.
Constants
Write a constant in capitals, in the class. Methods may reach it through the class or through self:
class Circle:
PI = 3.14159
def __init__(self, r):
self.r = r
def area(self):
return Circle.PI * self.r ** 2
def area2(self):
return self.PI * self.r ** 2
print(round(Circle(2).area(), 2), round(Circle(2).area2(), 2))
12.57 12.57
self.PI lets a subclass override the constant (lesson 13.5), but Circle.PI always uses the base class's.
4. Class methods
A normal method receives the object (self). A class method receives the class (cls). You mark it with the decorator @classmethod (lesson 11.11):
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod
def margherita(cls):
return cls(["tomato", "mozzarella"])
@classmethod
def from_string(cls, text):
return cls(text.split(","))
def __repr__(self):
return f"Pizza({self.ingredients})"
print(Pizza.margherita())
print(Pizza.from_string("ham,cheese,olives"))
Pizza(['tomato', 'mozzarella'])
Pizza(['ham', 'cheese', 'olives'])
Class methods are the standard way to write alternative constructors: other ways to create an object, with names that say what they do. Python allows only one __init__, so these fill the gap. They work on the class, with no object needed.
The reason to write cls(...) and not Pizza(...) inside: it works with subclasses. If Sub inherits from Pizza, then Sub.margherita() makes a Sub:
class Date:
def __init__(self, y, m, d):
self.y, self.m, self.d = y, m, d
@classmethod
def from_iso(cls, text):
y, m, d = map(int, text.split("-"))
return cls(y, m, d)
def __repr__(self):
return f"Date({self.y}, {self.m}, {self.d})"
class Sub(Date):
pass
print(Date.from_iso("2026-10-21"))
print(type(Sub.from_iso("2020-01-02")).__name__, type(Date.from_iso("2020-01-02")).__name__)
Date(2026, 10, 21)
Sub Date
Class methods can also work with class-level data, such as a registry:
class Registry:
_items = {}
@classmethod
def register(cls, name, value):
cls._items[name] = value
@classmethod
def get(cls, name):
return cls._items.get(name)
Registry.register("a", 1)
Registry.register("b", 2)
print(Registry.get("a"), Registry.get("z"))
1 None
5. Static methods
A static method receives neither the object nor the class. It is just a plain function that lives inside the class, because it belongs with it. Mark it with @staticmethod:
class Date2(Date):
@staticmethod
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(Date2.is_leap(2024), Date2.is_leap(1900))
print(Date2(2000, 1, 1).is_leap(2000))
True False
True
class Temp:
@staticmethod
def c_to_f(c):
return c * 9 / 5 + 32
@staticmethod
def f_to_c(f):
return (f - 32) * 5 / 9
print(Temp.c_to_f(100), round(Temp.f_to_c(98.6), 1))
212.0 37.0
You can call a static method on the class or on an object. It is useful for helpers related to the class. If it does not need the class's data, a plain function at module level is just as good, so use static methods sparingly, for grouping.
6. Three kinds of method
class M:
def inst(self):
return "instance", type(self).__name__
@classmethod
def cls_m(cls):
return "class", cls.__name__
@staticmethod
def stat():
return "static"
m = M()
print(m.inst(), m.cls_m(), m.stat())
print(M.cls_m(), M.stat())
('instance', 'M') ('class', 'M') static
('class', 'M') static
| Kind | First parameter | Can use | Called on | Use for |
|---|---|---|---|---|
| instance method | self (the object) |
the object's data and class data | an object | most methods |
| class method | cls (the class) |
class data, and can create objects | the class (or an object) | alternative constructors, class-level data |
| static method | none | nothing automatically | the class or an object | helpers that belong with the class |
An instance method called on the class needs the object as an argument:
M.inst()
TypeError: M.inst() missing 1 required positional argument: 'self'
7. A shared single object: the singleton
A class method plus a class attribute can ensure only one object exists:
class Singleton:
_instance = None
@classmethod
def get(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
print(Singleton.get() is Singleton.get())
True
Both calls return the same object. This pattern is used for things like a shared configuration. Use it rarely: shared state makes code harder to test.
Worked example: a Temperature class with all three kinds
An object holds a temperature in Celsius. A class attribute holds the freezing point, a class method creates a temperature from Fahrenheit, a static method checks whether a value is physically possible, and an instance method reports the state.
class Temperature:
FREEZING = 0.0
ABSOLUTE_ZERO = -273.15
created = 0
def __init__(self, celsius):
if not Temperature.is_possible(celsius):
raise ValueError("below absolute zero")
self.celsius = celsius
Temperature.created += 1
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5 / 9)
@staticmethod
def is_possible(celsius):
return celsius >= Temperature.ABSOLUTE_ZERO
def is_freezing(self):
return self.celsius <= self.FREEZING
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
t1 = Temperature(25)
t2 = Temperature.from_fahrenheit(14)
print(round(t2.celsius, 1), t2.is_freezing(), t1.is_freezing())
print(t1.to_fahrenheit(), Temperature.is_possible(-300))
print(Temperature.created)
try:
Temperature(-500)
except ValueError as e:
print("ValueError:", e)
-10.0 True False
77.0 False
2
ValueError: below absolute zero
| Part | Kind | Why |
|---|---|---|
FREEZING, ABSOLUTE_ZERO |
class attributes | constants for every temperature |
created |
class attribute | counts the objects, updated through the class name |
from_fahrenheit |
class method | an alternative way to build an object, with cls(...) |
is_possible |
static method | a plain check that needs no object, but belongs with the class |
is_freezing, to_fahrenheit |
instance methods | use this object's celsius |
The failed Temperature(-500) was refused before it was counted. The values are made up.
Common mistakes
- Changing a class attribute through an object (
obj.attr = ...creates a shadow). - Using
self.n += 1for a shared counter. UseClassName.n += 1. - A mutable class attribute used as per-object data. Create it in
__init__. - Writing
Pizza(...)inside a class method instead ofcls(...), which breaks subclasses. - Forgetting
@classmethodor@staticmethod, so the first argument is used asself. - Using a static method when it needs the class data. Use a class method.
Key takeaways
- A class attribute is written in the class body and shared by all objects; lookup tries the object first, then the class.
- Assigning through an object creates its own attribute and shadows the class one; change shared data through the class name.
@classmethodmethods getclsand are the way to write alternative constructors that work with subclasses.@staticmethodmethods get nothing automatically; they are plain helper functions grouped in the class.- Instance methods (the default) use the object; choose the kind by what the method needs.
Practice
1. Where do you write a variable so that all objects of a class share it?
Show answer
In the class body, outside any method: a class attribute.
2. After a.species = "x", does b.species change?
Show answer
No. The assignment creates a new attribute in a only, which hides the class attribute for a. b still sees the class value.
3. Fix this counter: def hit(self): self.n += 1 where n = 0 is at class level.
Show answer
Use the class name: Counter.n += 1 (or type(self).n += 1), so the shared attribute is changed, not a new instance attribute.
4. Write an alternative constructor from_pair(cls, text) that builds a Point from "3,4".
Show answer
@classmethod
def from_pair(cls, text):
x, y = map(int, text.split(","))
return cls(x, y)
5. Why write cls(...) rather than ClassName(...) in a class method?
Show answer
cls is whichever class the method was called on, so a subclass gets an object of its own type. A hard-coded name always builds the base class.
6. Which method kind receives nothing automatically?
Show answer
A static method (@staticmethod).