Sub topic 3
Class methods: methods that receive the class
This chapter assumes you can define classes and instance methods, use self and instance attributes, read @name decorator syntax, and tell class attributes from instance attributes. It covers what a class method is and what it receives. Alternative constructors, inheritance, and the choice between method types each get their own chapter.
The problem an instance method cannot solve
An instance method receives the object it was called on, as self. That works when the method needs one object's data. Sometimes the logic belongs to the class as a whole, such as a shared counter or a setting that every instance reads. An instance method can reach the class through self.__class__, but it needs an instance to do so. A class method does not need one.
Defining a class method
A class method is a method that receives the class as its first argument instead of an instance. You create one by putting the built-in @classmethod decorator above the function. By convention, the first parameter is named cls.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
return cls.count
print(Counter.increment()) # 1
print(Counter.increment()) # 2
print(Counter.count) # 2No instance exists anywhere in this program. Counter.increment() passes Counter itself as cls. The line cls.count += 1 reads the class attribute count and writes the new value back to the class.
cls is an ordinary parameter name, just as self is. Python does not treat either word specially. Everyone uses cls, so use it too.
What each call form passes
You can call a class method on the class or on an instance. Both calls give the method the same cls.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
return cls.count
c = Counter()
print(c.increment()) # 1
print(Counter.increment()) # 2
print(c.count) # 2When you call c.increment(), Python looks at the type of c, finds Counter, and passes that as cls. The instance c is not passed to the method at all. Inside the method you cannot see c.
Because the fence format requires the diagram label, here is the diagram in the required form.
Comparing the three first arguments
| Kind of method | Decorator | First argument | Can read instance data | Can read class data |
|---|---|---|---|---|
| Instance method | none | `self`, the instance | Yes | Yes, through `self` |
| Class method | `@classmethod` | `cls`, the class | No | Yes |
| Static method | `@staticmethod` | nothing extra | No | Only by naming the class |
Static methods get their own chapter. They are in the table so you can see the three kinds side by side.
A class method that uses class configuration
Class methods fit behavior that depends on class-level settings. This example formats a value using a prefix stored on the class.
class Ticket:
prefix = "TKT"
_next_number = 1
def __init__(self, number):
self.number = number
@classmethod
def next_label(cls):
label = f"{cls.prefix}-{cls._next_number:04d}"
cls._next_number += 1
return label
print(Ticket.next_label()) # TKT-0001
print(Ticket.next_label()) # TKT-0002The method reads cls.prefix and updates cls._next_number. Both belong to the class, so a class method is the natural place for this code. An instance method would force you to create a Ticket object just to ask for the next label.
Class methods and the instance
A class method cannot reach instance attributes, because it receives no instance. This code fails:
class Person:
def __init__(self, name):
self.name = name
@classmethod
def greet(cls):
return "Hello, " + cls.name
p = Person("Ada")
p.greet()Running it raises AttributeError, because name lives on the instance p and cls is the class Person. If a method needs self.name, it should be an instance method.
Common mistakes when you first write one
Forgetting the decorator is the most common mistake. Without @classmethod, Python treats the function as an instance method. Calling it on the class then raises a TypeError about a missing positional argument. Calling it on an instance silently passes the instance as the first parameter, so cls would actually hold an instance. That bug is hard to spot because the parameter name looks right.
Hard-coding the class name is another mistake. Writing Counter.count += 1 inside the method works for now, but it ignores the class the method was called on. Using cls keeps the method correct when someone later subclasses Counter. The inheritance chapter explains why.
A third mistake is expecting a class method to change per-object state. It receives only the class, so any attribute it assigns through cls lands on the class and is shared by every instance that does not shadow it with its own value.
Checking what you received
You can print cls to confirm what a class method receives. This is useful when a call behaves unexpectedly.
class Probe:
@classmethod
def show(cls):
print(cls)
print(cls is Probe)
Probe.show()
Probe().show()Both calls print <class '__main__.Probe'> and True. The second call goes through an instance, yet the method still sees the class.
Exercises
Exercise
A class Config has a class attribute debug = False. Write a class method enable_debug that sets debug to True for the class. Then explain what Config().debug returns after you call Config.enable_debug().
Show answer
class Config: debug = False @classmethod def enabledebug(cls): cls.debug = True Config.enabledebug() print(Config().debug) # True The method assigns through cls, so it changes the class attribute. A new instance has no instance attribute named debug, so it reads the class attribute and gets True.
Exercise
A developer writes def reset(cls): cls.count = 0 inside a class but forgets the @classmethod decorator. What happens when they call MyClass.reset(), and what happens when they call MyClass().reset()?
Show answer
Calling MyClass.reset() raises a TypeError because the function is an ordinary function in the class and receives no argument for cls. Calling MyClass().reset() passes the instance as the first argument, so cls holds an instance. The assignment cls.count = 0 then creates an instance attribute on that object and leaves the class attribute unchanged.