Sub topic 10
classmethod and staticmethod
This chapter assumes you know how __get__ works, the difference between data and non-data descriptors, and the lookup order from earlier chapters. Here you will see how classmethod and staticmethod use that machinery.
Two non-data descriptors
Both decorators wrap a function and store the wrapper in the class __dict__. Both define __get__ but not __set__, so they are non-data descriptors. They differ only in what __get__ returns.
| Decorator | What `__get__` returns | First argument the function receives |
|---|---|---|
| plain function | bound method, bound to the instance | the instance |
| `classmethod` | method bound to the class | the class |
| `staticmethod` | the original function, unchanged | none added |
A plain function called through the class gets no binding, because function.__get__(None, cls) returns the function itself. classmethod binds to a class in both cases.
A pure-Python model
You can rebuild both decorators in a few lines.
from types import MethodType
class MyClassMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if objtype is None:
objtype = type(obj)
return MethodType(self.func, objtype)
class MyStaticMethod:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
return self.func
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@MyClassMethod
def margherita(cls):
return cls(["mozzarella", "tomato"])
@MyStaticMethod
def is_valid(name):
return name.isalpha()
class Calzone(Pizza):
pass
print(type(Pizza.margherita()).__name__) # Pizza
print(type(Calzone(["ham"]).margherita()).__name__) # Calzone
print(Pizza.is_valid("ham")) # True
print(Pizza(["x"]).is_valid("ham1")) # FalseThe built-in versions behave the same way for these cases. MethodType(self.func, objtype) creates a bound method whose first argument is fixed to the class.
The second print shows why classmethod suits alternative constructors. When you call margherita on an instance of Calzone, __get__ receives objtype=Calzone. The lookup started from the instance's type, not from the class that defined the method. The factory therefore builds a Calzone, not a Pizza.
Where each one appears in the lookup
Because neither decorator defines __set__, an entry in the instance __dict__ shadows them:
class Tool:
@staticmethod
def run():
return "class version"
t = Tool()
t.__dict__["run"] = lambda: "instance version"
print(t.run()) # instance version
print(Tool.run()) # class versionThis is rarely a problem in practice. It follows from the lookup order, though, and it explains why assigning obj.method = something replaces the behavior for that one object only.
Inspecting the raw descriptor
Reading Pizza.__dict__["margherita"] skips __get__ and gives you the wrapper object. For the built-in decorators:
class Demo:
@classmethod
def cm(cls): ...
@staticmethod
def sm(): ...
print(type(Demo.__dict__["cm"]).__name__) # classmethod
print(type(Demo.__dict__["sm"]).__name__) # staticmethod
print(type(Demo.cm).__name__) # method
print(type(Demo.sm).__name__) # functionIf you copy a method out of vars(cls) and call it directly, it fails or misbehaves, because __get__ never ran. Use getattr(cls, name) when you want the normal result.
Exercise
A class defines @classmethod def make(cls): return cls(). A subclass Sub(Base) does not override make. What does Sub.make() return, and which argument does classmethod.__get__ receive that makes this happen?
Show answer
It returns a Sub instance. Sub.make calls __get__(None, Sub), so objtype is Sub, and the returned method is bound to Sub. The function runs with cls=Sub even though make is defined in Base.