Sub topic 3
Choosing the Right Kind of Method
Assume you know how to define classes, use self, distinguish class and instance attributes, and recognize decorator syntax such as @classmethod.
Choosing by Required State
Choose the method type by asking what data the operation needs:
| Method type | First argument | Use it when |
|---|---|---|
| Instance method | `self` | It reads or changes one object |
| Class method | `cls` | It reads or changes class-level behavior or creates an instance |
| Static method | None | It needs neither instance nor class state |
class Temperature:
unit = "C"
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
@classmethod
def from_fahrenheit(cls, value):
return cls((value - 32) * 5 / 9)
@staticmethod
def is_valid(value):
return value >= -273.15
temperature = Temperature.from_fahrenheit(212)
print(temperature.to_fahrenheit()) # 212.0
print(Temperature.is_valid(-300)) # FalseUse an instance method when the result depends on self. Use a class method for an alternative constructor or behavior that should follow the calling class. Use a static method for a related utility that does not need either kind of state.
Under the Hood: How Python Binds Methods
Functions stored in a class are descriptors. A descriptor is an object that controls what happens when an attribute is accessed.
When you access an ordinary function through an instance, Python binds the instance as the first argument. Accessing a class method binds the class as cls. A static method suppresses this automatic binding.
sequenceDiagram
participant Code
participant Python
participant Method
Code->>Python: item.work()
Python->>Method: bind item as self
Method-->>Code: result
Code->>Python: Item.make()
Python->>Method: bind Item as cls
Method-->>Code: new objectCommon Pitfalls
- Forgetting
@classmethodleavesclsunbound when calling the method on the class. - Forgetting
@staticmethodmakes Python pass an instance unexpectedly. - Hard-coding
Temperature(...)inside a class method breaks subclass-friendly behavior. Returncls(...)instead. - Calling a static method when it needs object data hides a design error. Make it an instance method.
- Calling a class method when each object has different required data can also be misleading.
Exercise
Which method type should validate a single numeric argument without reading an object or class attribute?
Show answer
A static method, because it needs no automatically supplied self or cls.