Sub topic 9
Common pitfalls and how to avoid them
This chapter assumes you can define classes, you know what self is, and you understand @name decorator syntax. It also assumes you know the difference between class attributes and instance attributes. Class methods and static methods are simple, but a few mistakes come up again and again. Each section below shows the mistake, what Python does, and the fix.
Pitfall 1: forgetting the decorator
Without @staticmethod or @classmethod, a function in a class body is an ordinary instance method. Python passes the instance as the first argument whether or not you declared a parameter for it.
class Converter:
def to_kelvin(celsius):
return celsius + 273.15
print(Converter.to_kelvin(0)) # 273.15, works by accident
try:
print(Converter().to_kelvin(0))
except TypeError as error:
print(error)Calling through the class works, because no instance is bound. Calling through an instance fails with a TypeError that says the method takes 1 positional argument but 2 were given. The first form hides the bug, so tests that only use the class can pass while real code breaks.
The fix is to add @staticmethod above the function. If the function needs the class, add @classmethod and a cls parameter instead.
Pitfall 2: hard-coding the class name
A class method receives the class it was called on. If you write the class name inside the method, you throw that information away.
class Shape:
@classmethod
def create_bad(cls):
return Shape()
@classmethod
def create_good(cls):
return cls()
class Square(Shape):
pass
print(type(Square.create_bad()).__name__) # Shape
print(type(Square.create_good()).__name__) # Squarecreate_bad always builds a Shape, so subclasses silently get the wrong type. Use cls anywhere you would have written the class name.
Pitfall 3: class state that is shared or shadowed
Reading cls.count finds the attribute on the class or on a parent. Assigning to it always writes to the exact class you called the method on. Combined, these two rules surprise people.
class Base:
count = 0
@classmethod
def increment(cls):
cls.count += 1
class Child(Base):
pass
Base.increment()
Child.increment()
Child.increment()
print(Base.count) # 1
print(Child.count) # 3The line cls.count += 1 expands to cls.count = cls.count + 1. On the first Child.increment(), the right side reads Base.count (1). The left side then creates a new attribute on Child with the value 2. From then on Child has its own counter, and Base.increment() no longer affects it.
Decide which behavior you want:
- For one counter shared by the whole hierarchy, name the class that owns it:
Base.count += 1. This is a deliberate exception to the "never hard-code the class" rule. - For an independent counter per subclass, keep
cls.countand give each class its own starting value, or set it in__init_subclass__.
Pitfall 4: an alternative constructor that assumes `__init__`
An alternative constructor ends with cls(...), so it calls the subclass's __init__. If a subclass changes the signature of __init__, the inherited constructor breaks.
class Date:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_string(cls, text):
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
class LabeledDate(Date):
def __init__(self, year, month, day, label):
super().__init__(year, month, day)
self.label = label
try:
LabeledDate.from_string("2026-11-26")
except TypeError as error:
print(error)from_string passes three arguments, but LabeledDate.__init__ requires four. There are two fixes. You can keep subclass signatures compatible by giving label a default. Or you can override from_string in the subclass. Either way, document which constructor signature subclasses must keep.
Pitfall 5: using a static method when you need the class or instance
A static method receives nothing, so it cannot see cls or self. If you find yourself writing the class name inside a static method to reach its data, the method wants to be a class method.
A related mistake runs the other way. A class method that never uses cls is probably a static method. A method that never uses self or cls and has nothing to do with the class might belong as a plain module-level function.
Pitfall 6: stacking decorators the old way
Combining @classmethod with @property was deprecated in Python 3.11 and removed in 3.13. Code that relied on it fails on current versions. Use a plain class method, such as Config.default(), or a custom descriptor if you need property-like access on the class.
When you combine @classmethod with decorators that wrap functions, such as caching, put @classmethod on the outside (the top line). It must wrap the finished function.
A quick decision check
When you are unsure which kind of method to write, ask what the method needs to touch.
Checklist
- Every method without
selfhas a decorator, or it is a deliberate mistake you will fix. - Methods that create instances use
cls(...), not a class name. - Writes to class attributes go to the class you mean.
- Subclasses keep the
__init__signature that inherited constructors expect. - No
@classmethodstacked on@propertyin code that must run on Python 3.13 or later.
Exercise
A class Base has registry = [] and a class method add(cls, item) that runs cls.registry.append(item). A subclass Child does not define its own registry. After Child.add("x"), does Base.registry contain "x"? Compare this with changing the method body to cls.registry = cls.registry + [item].
Show answer
Yes, the first version puts "x" in Base.registry. cls.registry.append(item) only reads the attribute, which finds the list on Base, and then mutates that shared list in place. No assignment happens, so no new attribute is created on Child. The second version assigns, so Child gets its own new list containing "x" and Base.registry stays unchanged. Mutating shares state, and assigning shadows it.
Exercise
This method is meant to be a utility on class Money, but Money().convert(5) raises a TypeError. What is wrong, and how do you fix it?
class Money:
def convert(amount):
return amount * 2
Show answer
The decorator is missing, so Python treats convert as an instance method and passes the instance as amount, which makes two arguments for one parameter. Add @staticmethod above def convert(amount):. Then both Money.convert(5) and Money().convert(5) return 10.