Sub topic 3
Class methods: methods that receive the class
What this chapter assumes
This chapter assumes you can already:
- Define a class and write instance methods that use
self. - Read and set instance attributes.
- Tell a class attribute from an instance attribute.
- Recognize decorator syntax (
@nameon the line above a function), without needing to write decorators yourself.
By the end you will be able to write a class method with @classmethod and say what cls refers to. You will also be able to call it through the class or an instance, and use it to read and change class-level state.
The problem: behavior that belongs to the class
An instance method works on one object. Python passes that object as the first argument, and by convention you call it self. Some behavior does not belong to any single object. It concerns the class as a whole:
- Changing a setting shared by every instance.
- Reading a counter that tracks all instances.
- Building a new instance from unusual input (the next chapter covers this in detail).
You can write these as ordinary functions outside the class, but then the code is separated from the data it manages. A class method keeps it inside the class. It is an ordinary-looking method whose first argument is the class, not an instance.
Defining a class method
Put @classmethod on the line above the def, and name the first parameter cls.
class Employee:
raise_factor = 1.5
def __init__(self, name, pay):
self.name = name
self.pay = pay
def apply_raise(self):
self.pay = self.pay * self.raise_factor
@classmethod
def set_raise_factor(cls, factor):
cls.raise_factor = factor
ana = Employee("Ana", 100)
ana.apply_raise()
print(ana.pay) # 150.0
Employee.set_raise_factor(2.0)
ana.apply_raise()
print(ana.pay) # 300.0set_raise_factor has no self. It never needs a particular employee. It changes raise_factor, which lives on the class, so every employee sees the new value.
cls is not a keyword. It is a parameter name, like self. Python fills it in when you call the method, and everyone uses cls by convention. Other Python programmers, linters, and editors expect that name. (class is a reserved word, so you cannot use it as a parameter name. That is why the convention is cls.)
What `cls` actually is
cls is the class object itself. You can check this:
class Employee:
@classmethod
def whoami(cls):
print(cls)
print(cls is Employee)
Employee.whoami()
# <class '__main__.Employee'>
# TrueBecause cls is the class, you can do anything with it that you could do with Employee written out:
- Read class attributes:
cls.raise_factor. - Assign class attributes:
cls.raise_factor = 2.0. - Call other class methods:
cls.set_raise_factor(2.0). - Call the class to make an instance:
cls("Ana", 100).
The last item is the most useful, and the next chapter builds on it.
Calling a class method
You can call a class method on the class or on an instance. Both calls pass the class as cls.
class Employee:
raise_factor = 1.5
@classmethod
def set_raise_factor(cls, factor):
cls.raise_factor = factor
a = Employee()
b = Employee()
a.set_raise_factor(2.0) # called through an instance
print(Employee.raise_factor) # 2.0
print(b.raise_factor) # 2.0The call a.set_raise_factor(2.0) does not pass a. Python looks at the method, sees it is a class method, and passes type(a) instead. Here that is Employee. The instance is discarded. Compare the two kinds of method:
| Call | Method kind | First argument received |
|---|---|---|
| `obj.method()` | instance method | `obj` |
| `Cls.method(obj)` | instance method | `obj` (passed explicitly) |
| `Cls.method()` | class method | `Cls` |
| `obj.method()` | class method | `type(obj)` |
Calling through an instance works, but calling through the class is clearer. A reader who sees a.set_raise_factor(2.0) may think the change affects only a. Write Employee.set_raise_factor(2.0) so the code says what it does.
Class methods and class attributes
A class method is the natural place to read or change class attributes. You need to know one rule about assignment, because it explains most surprises.
- Reading
cls.namesearches the class and then its parent classes. - Assigning
cls.name = valuealways creates or replaces the attribute onclsitself.
The same rule applies to instances. Assigning through an instance creates an instance attribute that hides the class attribute for that one object:
class Employee:
raise_factor = 1.5
@classmethod
def set_raise_factor(cls, factor):
cls.raise_factor = factor
a = Employee()
b = Employee()
a.raise_factor = 3.0 # instance attribute, shadows the class value
Employee.set_raise_factor(4.0) # changes the class attribute
print(a.raise_factor) # 3.0 (own value wins)
print(b.raise_factor) # 4.0 (falls back to the class)
print(a.__dict__) # {'raise_factor': 3.0}A class method cannot repair the shadowed value on a. It only sees the class. If you want every instance to follow the class value, do not assign that attribute on instances.
A shared counter
Counting how many instances exist is a typical use. The counter belongs to the class, and a class method reports it:
class Connection:
_open_count = 0
def __init__(self, host):
self.host = host
Connection._open_count += 1
@classmethod
def open_count(cls):
return cls._open_count
Connection("db1.example.com")
Connection("db2.example.com")
print(Connection.open_count()) # 2A leading underscore on _open_count marks it as internal. It is only a naming convention. Python does not enforce it. The class method gives callers a public way to read the value.
__init__ writes Connection._open_count with the class name written out, because an instance method has no cls. Writing the name is acceptable for a counter shared by all instances. Chapter 6 covers when it becomes a problem with subclasses.
A registry
A class method can also modify a mutable class attribute, such as a list or dictionary:
class Plugin:
registry = []
@classmethod
def register(cls, name):
cls.registry.append(name)
@classmethod
def names(cls):
return list(cls.registry)
Plugin.register("csv")
Plugin.register("json")
print(Plugin.names()) # ['csv', 'json']Here cls.registry.append(name) does not assign to cls.registry. It reads the list and mutates it in place. That is why it works without creating a new attribute. names returns a copy with list(...), so callers cannot change the registry by editing the result.
`cls.x += 1` creates an attribute on the subclass
The assignment rule above has a consequence for subclasses. Consider a counter incremented in a class method:
class Base:
count = 0
@classmethod
def bump(cls):
cls.count += 1
class Child(Base):
pass
Child.bump()
print(Base.count) # 0
print(Child.count) # 1cls.count += 1 means cls.count = cls.count + 1. The right side reads Base.count (0) by inheritance. The left side assigns on Child, creating a new Child.count that is now independent of Base.count. If you wanted one shared counter, write Base.count += 1. If you wanted one counter per class, cls.count += 1 is what you want, but you should do it on purpose. The later chapter on inheritance covers this design choice.
What a class method cannot do
A class method receives no instance, so it has no self. It cannot read instance attributes:
class Employee:
def __init__(self, name):
self.name = name
@classmethod
def describe(cls):
return cls.name
try:
Employee.describe()
except AttributeError as error:
print(error)
# type object 'Employee' has no attribute 'name'name exists only on instances created by __init__. The class has no name. If a method needs per-object data, it should be an instance method.
Forgetting the decorator
Without @classmethod, a method with a cls parameter is still an instance method. The name cls means nothing to Python. The first argument is whatever is passed, and when you call through the class, nothing is passed:
class Broken:
def make(cls):
return cls()
try:
Broken.make()
except TypeError as error:
print(error)
# Broken.make() missing 1 required positional argument: 'cls'The exact wording varies by Python version. Older versions print make() missing 1 required positional argument: 'cls'. The cause is the same: Broken.make is a plain function, and no instance supplied the first argument.
The reverse mistake is subtler. Calling the method through an instance does appear to work, because the instance is passed in as the first argument. The parameter named cls then holds an instance, not a class:
class Broken:
def make(cls):
return cls
print(Broken().make()) # <__main__.Broken object at 0x...>Nothing fails here, which is why this mistake can sit in code unnoticed. The parameter name no longer matches what it holds, and calls like cls() later raise confusing errors such as 'Broken' object is not callable. If a method is meant to be a class method, check that the decorator is directly above the def.
Class methods versus module-level functions
You could write set_raise_factor as a plain function:
def set_raise_factor(factor):
Employee.raise_factor = factorIt works, but it hard-codes the class name, lives away from the class, and is not found through the class. A class method:
- Stays with the class it manages, in the same file and namespace.
- Is found by the usual
Employee.lookup, and shows up indir(Employee)and in documentation tools. - Receives the class automatically, so the body does not repeat the name.
- Receives the right class when called on a subclass, which the later inheritance chapter shows.
None of this makes class methods always better. A function that does not need the class at all is a different case, and the chapter on choosing method types covers it.
A worked example
This example combines the pieces: a class attribute, class methods that read and change it, and an instance method that uses it.
class Product:
tax_rate = 0.25
created = 0
def __init__(self, name, price):
self.name = name
self.price = price
Product.created += 1
def price_with_tax(self):
return self.price * (1 + self.tax_rate)
@classmethod
def set_tax_rate(cls, rate):
if rate < 0:
raise ValueError("tax rate cannot be negative")
cls.tax_rate = rate
@classmethod
def how_many(cls):
return cls.created
book = Product("Book", 40)
pen = Product("Pen", 8)
print(book.price_with_tax()) # 50.0
Product.set_tax_rate(0.5)
print(book.price_with_tax()) # 60.0
print(pen.price_with_tax()) # 12.0
print(Product.how_many()) # 2Follow the data:
tax_rateandcreatedare stored once, onProduct.__init__runs per instance, and each run bumps the sharedcreatedcounter.price_with_taxis an instance method. It usesself.price(per object) andself.tax_rate. That lookup finds the class value because no instance has its own.set_tax_rateis a class method. It validates the input and then updates the single stored value, so both products see 0.5.how_manyis a class method because it asks about the class, not any one product.
The validation in set_tax_rate is a practical benefit. Direct assignment (Product.tax_rate = -1) skips any check, while the class method is one place to put the rule.
Summary of the model
- A class method is declared with
@classmethodand receives the class as its first argument, namedclsby convention. - It can be called on the class or on an instance. Either way
clsis the class (for an instance call,type(instance)). - It can read and assign class attributes and call other class methods. It cannot see instance attributes.
- Assigning through
clswrites to that exact class. Mutating a shared object changes it for every class that inherits it. - A method with a
clsparameter but no decorator is an ordinary instance method, and it fails or misbehaves.
The next chapter takes the last bullet under "what cls can do" and uses cls(...) to build instances from alternative inputs.
Exercise
What does this code print, and why? class Settings: debug = False @classmethod def enabledebug(cls): cls.debug = True s1 = Settings() s2 = Settings() s1.debug = False s1.enabledebug() print(Settings.debug, s1.debug, s2.debug)
Show answer
It prints True False True. s1.enable_debug() passes Settings as cls, so Settings.debug becomes True. s2 has no debug of its own and reads the class value, True. The line s1.debug = False earlier created an instance attribute on s1, which shadows the class attribute. The class method cannot change it, so s1.debug stays False.
Exercise
Write a class Counter with a class attribute total starting at 0. Add an instance method add(n) that adds n to total on the class (not on the instance), and a class method reset() that sets total back to 0. Show that two instances share the total.
Show answer
One solution:
class Counter:
total = 0
def add(self, n):
Counter.total += n
@classmethod
def reset(cls):
cls.total = 0
a = Counter()
b = Counter()
a.add(5)
b.add(3)
print(Counter.total) # 8
Counter.reset()
print(a.total) # 0
add writes through Counter, not self. Writing self.total += n would create an instance attribute on each object and the totals would not be shared. reset is a class method because it changes class state and needs no instance.
Exercise
A teammate writes the method below and reports TypeError: Registry.create() missing 1 required positional argument: 'cls' when calling Registry.create(). What is the fix?
class Registry:
def create(cls):
return cls()
Show answer
Add @classmethod on the line above def create(cls):. Without the decorator, create is a plain function stored on the class, so Registry.create() supplies no first argument. With the decorator, Python passes Registry as cls, and cls() returns a new Registry instance.