Sub topic 7
Choosing the right kind of method
This chapter assumes you can define classes and instance methods, know what self is, and can tell class attributes from instance attributes. You should also have seen @classmethod and @staticmethod once. Here you learn to decide which kind of method a piece of behavior belongs in.
Ask what the method needs
The decision depends on what the method reads or changes. Python does not enforce it. Any of the three kinds will run, but the wrong choice makes code harder to extend.
| Kind | First argument | Needs | Typical use |
|---|---|---|---|
| Instance method | `self` | One object's data | Behavior of a single object |
| Class method | `cls` | The class, or the ability to create instances of it | Alternative constructors, shared class state |
| Static method | none | Nothing from the object or class | Helper tied to the class's purpose |
One class, three choices
The Account class below uses each kind where it fits.
class Account:
interest_rate = 0.02
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if not self.is_valid_amount(amount):
raise ValueError("amount must be positive")
self.balance += amount
@classmethod
def from_record(cls, record):
owner, balance = record.split(",")
return cls(owner, float(balance))
@classmethod
def set_rate(cls, rate):
cls.interest_rate = rate
@staticmethod
def is_valid_amount(amount):
return amount > 0
acct = Account.from_record("Ana,150.5")
acct.deposit(50)
print(acct.balance) # 200.5
Account.set_rate(0.03)
print(Account.interest_rate) # 0.03Each method follows the decision flow:
depositchangesself.balance, so it must be an instance method.from_recordhas no instance yet. It needs the class so it can callcls(...), so it is a class method.set_ratechanges state shared by the whole class, so it takescls.is_valid_amountuses only its argument. It belongs withAccountbecause the rule is about account amounts, but it needs neitherselfnorcls.
Notice that deposit calls self.is_valid_amount, not Account.is_valid_amount. A subclass can then override the rule, and deposit will use the override. Writing the class name would lock deposit to the base rule.
Class methods that change state and subclasses
cls is whichever class the method was called on. When a class method assigns to cls.interest_rate, that decides where the value is stored:
class Savings(Account):
pass
Account.set_rate(0.03)
Savings.set_rate(0.05)
print(Savings.interest_rate, Account.interest_rate) # 0.05 0.03Calling set_rate on Savings created a new attribute on Savings and left Account alone. That may be what you want or it may be a surprise. When you write a class method that modifies state, decide whether each subclass should have its own value or all classes should share one. If they should share, name the base class explicitly or keep the value in a single place.
Signs you picked the wrong kind
A few patterns show up often in review:
- An instance method that never touches
self. If it only uses its arguments, it can be a static method. If it builds objects of the same class, it should be a class method. - A class method that never touches
cls. The parameter is dead weight. Use a static method instead. - A static method that builds instances by naming the class. This breaks under inheritance, as shown below.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def origin():
return Point(0, 0) # always a Point, even when called on a subclass
class Point3D(Point):
pass
print(type(Point3D.origin()).__name__) # PointChanging the decorator to @classmethod and returning cls(0, 0) makes Point3D.origin() return a Point3D. In general, if a method creates instances of its own class, it needs cls.
Static method or plain function?
A static method is an ordinary function stored in the class namespace. It is not a different kind of function with extra abilities. Ask whether callers would find it naturally by looking at the class.
- Keep it as a static method when it expresses a rule of the class, such as
Account.is_valid_amount. A subclass can then override the rule, andself.is_valid_amount(...)will use the override. - Make it a module-level function when it is a general utility, such as a string formatter used in many places. Putting it in a class adds a prefix and nothing else.
If you are unsure, start with a module-level function. Moving it into a class later is easy.
Quick checklist
- Does it use data from one specific object? Use an instance method.
- Does it create instances, or read or change class-level state? Use a class method.
- Does it use neither, but belong with the class conceptually? Use a static method.
- Does it have no real connection to the class? Use a module-level function.
Exercise
A class Report has a method parse_title(line) that strips a leading "Title:" prefix from a string and returns the rest. It uses no attributes of any Report object. Another method, from_file(path), reads a file and returns a new report. Which kind of method should each be, and why?
Show answer
parse_title should be a static method (or a module-level function). It uses only its argument, so it needs neither self nor cls. from_file should be a class method, because there is no instance yet and it must create one. Returning cls(...) also makes it produce a subclass instance when called on a subclass.
Exercise
This code prints Base. Change one thing so that Child.make() returns a Child, and say what the method kind becomes.
class Base:
@staticmethod
def make():
return Base()
class Child(Base):
pass
print(type(Child.make())._name_)
Show answer
Make make a class method that returns cls(): @classmethod, def make(cls): return cls(). It then receives the class it was called on, so Child.make() returns a Child and the program prints Child.