Sub topic 7
Choosing the right kind of method
This chapter assumes you can already write a class with an __init__ method and instance methods that use self. You should know that @name above a function is a decorator. You should also know the difference between a class attribute and an instance attribute. Earlier chapters covered how @classmethod and @staticmethod work. This chapter is about the decision: given a piece of behavior, which kind of method should hold it, and what goes wrong when you choose badly?
The one question that decides most cases
Ask what the method needs in order to do its job.
- It needs the data of one particular object. Use an instance method. It receives
self. - It needs the class itself, to build instances or to read or change class-level data. Use a class method. It receives
cls. - It needs neither. It is an ordinary function that happens to belong with the class. Use a static method, or a plain module-level function.
A quick test is to write the method with its first parameter, then read the body. If the body never uses self, the method probably should not be an instance method. If it uses cls but never self, it is a class method. If it uses neither, it is static, or it belongs outside the class.
| Method type | First argument | Can read instance data | Can read or change class data | Can build instances of the right class | Typical use |
|---|---|---|---|---|---|
| Instance method | `self` | Yes | Yes, through `self` or `type(self)` | Yes, through `type(self)` | Behavior of one object |
| Class method | `cls` | No | Yes | Yes, through `cls(...)` | Alternative constructors, class-wide settings |
| Static method | None | No | Only by naming the class | Only by naming the class | Helpers grouped with a class |
A decision flow
The diagram turns the question above into a sequence of checks. It adds one extra branch at the end, because a static method is not always the best home for a helper.
One class that uses all three
The following class has one method of each kind, and each choice follows from what the method needs.
import datetime
class Employee:
raise_rate = 1.03
def __init__(self, name, salary):
self.name = name
self.salary = salary
def apply_raise(self):
self.salary = round(self.salary * self.raise_rate, 2)
@classmethod
def from_string(cls, text):
name, salary = text.split(",")
return cls(name.strip(), float(salary))
@classmethod
def set_raise_rate(cls, rate):
if not cls.is_valid_rate(rate):
raise ValueError("rate must be between 1.0 and 1.5")
cls.raise_rate = rate
@staticmethod
def is_valid_rate(rate):
return 1.0 <= rate <= 1.5
@staticmethod
def is_workday(day):
return day.weekday() < 5
e = Employee.from_string("Ada, 50000")
e.apply_raise()
print(e.salary) # 51500.0
Employee.set_raise_rate(1.05)
print(e.raise_rate) # 1.05
print(Employee.is_workday(datetime.date(2026, 11, 26))) # TrueHere is the reasoning behind each choice:
apply_raisechanges one employee's salary, so it needsself.from_stringhas no object yet. It exists to create one, and it usescls(...)so that subclasses get instances of their own type.set_raise_ratechanges a value shared by every employee, so it works on the class.is_valid_rateandis_workdayonly look at their arguments. They are static.
Notice that set_raise_rate calls cls.is_valid_rate(rate) and does not call Employee.is_valid_rate(rate). A subclass can override the validation rule, and the class method will pick up the override. Static methods are still looked up through the class, so they remain overridable as long as callers go through cls or self.
Choosing between a class method and an instance method
The line between these two is mostly about what the method modifies. An instance method that updates class-level data through self can silently do the wrong thing.
class Counter:
total = 0
def bump_wrong(self):
self.total += 1 # reads Counter.total, then creates an instance attribute
@classmethod
def bump(cls):
cls.total += 1
a = Counter()
a.bump_wrong()
print(a.total, Counter.total) # 1 0
Counter.bump()
b = Counter()
print(Counter.total, b.total) # 1 1The statement self.total += 1 reads the class attribute, adds one, and then assigns the result to self.total. Assignment through self always creates or updates an instance attribute. The shared value is never touched. If the intent is to change shared state, a class method says so in its signature and avoids this trap.
The same rule applies inside class methods when subclasses are involved. Assignment through cls writes to the class the method was called on, not to the class where it was defined.
class Counter:
total = 0
@classmethod
def bump(cls):
cls.total += 1
class Sub(Counter):
pass
Counter.bump()
Sub.bump()
print(Sub.total, Counter.total) # 2 1The call Sub.bump() read Counter.total (which was 1) through inheritance, added one, and stored 2 as a new attribute on Sub. From then on the two counters are independent. Whether that is correct depends on your design:
- If each subclass should keep its own count,
cls.total += 1is right, though you may want to give each class its own starting value explicitly. - If all subclasses must share one count, name the class on purpose:
Counter.total += 1.
This is one of the few places where hard-coding the class name is the correct choice, because you want the shared value and not the per-subclass one. Add a comment so the next reader does not "fix" it.
Choosing between a class method and a static method
Both can be called on the class without an instance. The difference is whether the method needs to know which class it was called on. The clearest case is a factory that returns an instance.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def origin():
return Point(0, 0) # class name hard-coded
@classmethod
def unit_x(cls):
return cls(1, 0) # follows the class it was called on
class Point3(Point):
pass
print(type(Point3.origin()).__name__) # Point
print(type(Point3.unit_x()).__name__) # Point3Point3.origin() returns a plain Point, which is rarely what a caller expects from a method on a subclass. A static method that constructs or inspects its own class by name is a signal to switch to @classmethod. The fix costs one decorator and one renamed parameter.
The reverse is also a smell. A class method that never uses cls should be static, because the extra parameter promises a dependency that does not exist.
Choosing between a static method and a module-level function
Python does not require every function to live in a class. A static method is only a function stored in the class namespace. So the question is whether putting it there helps.
| Consideration | Static method | Module-level function |
|---|---|---|
| Discoverability | Found next to the class it supports, visible in `help(Class)` | Found by reading the module |
| Call syntax | `Class.helper(x)` or `self.helper(x)` | `helper(x)` |
| Overriding in subclasses | Possible, if callers use `cls.helper` or `self.helper` | Not possible without changing the call site |
| Import cost | Comes with the class | Must be imported separately if used elsewhere |
| Simplicity | One extra decorator and indentation level | Nothing extra |
Use a static method when the helper is part of the class's contract. For example, it validates the values the class accepts, or a subclass might reasonably replace it. Use a module-level function when the helper is generic and is used by several unrelated classes. Examples are a string-parsing utility or a math routine. Many Python codebases lean toward module-level functions by default. A static method is a deliberate choice, not a reflex, and it is not required in order to "put a function in a class".
When a method should not be a method at all
Two more cases are worth recognizing.
- A method with no arguments other than
selfthat returns a value computed from instance data is often better as a@property. Callers then writeobj.areainstead ofobj.area(). - A class method that only reads a class attribute and returns it adds little. Callers can read
Class.attributedirectly.
Use a method when the call performs an action, takes arguments, or may fail. Use an attribute or property when it is just a value.
Worked refactor
Here is a class where every method was written as an instance method out of habit.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def from_fahrenheit(self, fahrenheit):
return Temperature((fahrenheit - 32) * 5 / 9)
def is_valid(self, celsius):
return celsius >= -273.15
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32Apply the test from the start of the chapter to each method:
to_fahrenheitusesself.celsius. It stays an instance method.from_fahrenheitignoresself. Its job is to create a new object, and it hard-codesTemperature. As written, you would need an existing object just to call it. Make it a class method that returnscls(...).is_validignoresselfand does not create anything. Make it static.
class Temperature:
def __init__(self, celsius):
if not self.is_valid(celsius):
raise ValueError("below absolute zero")
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit - 32) * 5 / 9)
@staticmethod
def is_valid(celsius):
return celsius >= -273.15
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
print(Temperature.from_fahrenheit(212).celsius) # 100.0
print(Temperature.is_valid(-300)) # FalseThe refactor also changes __init__ to call self.is_valid, which is allowed because static methods can be reached through an instance. This reuses the rule in one place, and a subclass can override is_valid to change what counts as acceptable.
Common wrong choices
| Symptom in the code | Likely problem | Better choice |
|---|---|---|
| Instance method that never uses `self` | The method does not depend on the object | Static method, or a module function |
| Static method that returns `ClassName(...)` | Subclasses get the wrong type | Class method using `cls(...)` |
| Class method that never uses `cls` | The parameter promises something false | Static method |
| `self.shared_value += 1` on a class attribute | Creates an instance attribute and leaves the shared value alone | Class method that writes `cls.shared_value`, or `ClassName.shared_value` if sharing is the intent |
| Class method that needs `self.something` | It needs an instance after all | Instance method |
| Helper used by many unrelated classes, defined as a static method on one of them | Wrong home for the helper | Module-level function |
Effects on testing and design
Your choice also changes how easy the code is to test and extend.
- Static methods are the easiest to test. They take inputs and return outputs, with no object setup.
- Class methods need only the class. Tests can call
Employee.from_string("Ada, 50000")and check the result, and they can call it on a subclass to confirm the subclass type is preserved. - Instance methods need a constructed object. If constructing one is expensive, ask whether part of the logic could be moved into a static helper that takes plain values.
When you design for inheritance, a useful habit is to make every constructor-like method a class method that calls cls(...). Other code then keeps working when someone subclasses your class. That includes code you have not written yet.
A short checklist
Before you commit to a method type, check these points:
- Does the body use
self? If so, it is an instance method. - Does the body use
cls, or does it need to create or configure "this class or a subclass"? If so, it is a class method. - Does it use neither? If so, decide between a static method and a module-level function based on whether it belongs to the class's contract.
- Does it assign to shared state? Check whether the assignment goes to the class you intend.
- Does any code inside the class hard-code the class name? Ask whether a subclass should get its own behavior there.
Exercise
A class Report has the method def new_empty(): return Report([]) defined with @staticmethod. A subclass PdfReport(Report) calls PdfReport.new_empty() and gets a plain Report. Rewrite the method so that it returns a PdfReport when called on PdfReport, and say which method type you used.
Show answer
Use a class method: @classmethod followed by def new_empty(cls): return cls([]). The method creates an instance and must follow the class it was called on, so it needs cls. A static method cannot know which class called it, which is why the hard-coded Report was returned.
Exercise
Classify each as instance, class, or static: (a) Account.deposit(amount) changes one account's balance; (b) Account.from_json(text) builds an account from JSON; (c) Account.is_valid_iban(text) checks a string format without reading any account or class data; (d) Account.set_default_currency(code) changes a value shared by all accounts.
Show answer
(a) instance method, because it changes the state of one object. (b) class method, because it builds an instance and should use cls(...) so subclasses work. (c) static method, because it only looks at its argument. A module-level function is also reasonable if other classes need it. (d) class method, because it assigns to class-level data through cls.
Exercise
Given class A: count = 0 with @classmethod def add(cls): cls.count += 1 and class B(A): pass, what do A.count and B.count print after A.add() and then B.add()? How would you make both calls update one shared counter?
Show answer
They print 1 and 2. B.add() reads the inherited value 1 and stores 2 as a new attribute on B, so A.count stays 1. To share one counter, write A.count += 1 inside the method, naming the class on purpose, and add a comment explaining that the sharing is intended.