Definition
Sometimes a method has no use for one precise object: what it wants is the class, to read a value common to every object or to build one from raw data. With an ordinary method the work gets stuck: you already need an instance in hand to call it. The classmethod lifts that blockage.
It is a method that receives the class itself as its first parameter, where an ordinary method receives the object. It is declared with a decorator placed right above the def, and its first parameter is named cls by convention, rather than self.
cls is not a keyword: Python would accept any name here, as it does for self. But everyone reads it as "the class arrives", and departing from it costs the reviewer more time than it saves.
The shortest possible example holds a class, a shared value, and a method that goes and reads it.
class User:
domain = "believemy.com" # value shared by the whole class
@classmethod
def sample_address(cls): # cls is User
return f"first.last@{cls.domain}"
print(User.sample_address()) # called straight on the class
# first.last@believemy.comNo object was created here, and that is the first thing this writing brings: the method is available before any instance even exists.
The three kinds of method
This writing has two neighbours it often gets mixed up with. A class holds three sorts of function, told apart by what they receive first: in the table, the middle column is the one in charge.
| Written | First parameter | What it is for |
|---|---|---|
| Instance method | The object, named self | Working on the data of one precise object |
@classmethod | The class, named cls | Building an object or reading a class attribute |
@staticmethod | Nothing at all | Filing a helper function next to its subject |
The choice is settled with a single question: what does the method need? The data of one precise object, and it takes self. The class, and it takes cls. Neither one, and it should receive nothing. The property does not play in this category: it changes how the method is called, not what it receives.
The alternative constructor
This is by far the main use, and it is best approached from the nuisance it settles. The __init__ describes a single way in: the one where data arrives clean and separated, one argument per piece of information. Yet it rarely arrives that way, since a file hands over a line of text and a form a string to be cut up.
That tidying can be done in the calling code. It holds once, then the same cutting turns up copied in three places, and the day the format changes all three have to be found again. A classmethod adds a second door to the class, without touching the first.
class Client:
def __init__(self, first_name, last_name): # the official way in
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_line(cls, line): # the second door
first_name, last_name = line.split(";")
return cls(first_name.strip(), last_name.strip()) # then back through __init__
client = Client.from_line("Marie ; Dupont")Two details matter. The cutting done by split stays locked inside the method, and the rest of the program has only one name to remember. The last line calls cls(...), that is, the normal constructor: a classmethod never replaces __init__, it prepares the ground for it.
The standard library is full of them: dict.fromkeys, datetime.now, datetime.fromtimestamp. The name there almost always announces the raw material, and naming yours that way makes its role readable with no documentation.
What cls changes about inheritance
So far, naming Client in hard form would have given the same result. The real benefit of cls shows up as soon as a class is derived: since it points at the class actually called, and not at the one where the code was written, the alternative constructor builds the right type in subclasses.
class ProClient(Client):
discount = 0.2 # the subclass only adds a value
c = ProClient.from_line("Marie ; Dupont")
print(type(c))
# <class '__main__.ProClient'>The subclass redefined nothing, and yet it inherits a constructor that hands it objects of its own type. In hard form, the call would have handed back an ordinary Client without flagging a thing, and the defect would have stayed invisible until the first read of discount. That is why inheritance and this writing go together so often.
The mistakes that keep coming back
The most frequent one is the forgotten at sign. Without its decorator, a method declaring cls stays an ordinary instance method: calling it on the class raises a TypeError, but calling it on an object passes without a word, with a cls holding the object.
The second touches values changed on the class, a counter for instance. cls.counter += 1 looks like incrementing one single total: true as long as the call comes from the original class, false as soon as it comes from a subclass.
cls.counter += 1 reads the parent counter but writes the result onto the subclass, which ends up with a counter of its own hiding the other. The two totals then drift apart in silence. For a common counter, name the original class: Client.counter += 1.
The third is the choice of tool: whatever needs neither the object nor the class has no business here. A plain module-level function reads just as well and tests better.
Frequently asked questions
Can it be called on an instance?
Yes, and the result is identical: Python walks up to the class of the object before passing it into cls. Calling it on the class stays preferable, since it announces that no data of the object comes into play.
How does it differ from a staticmethod?
The first receives the class, the second receives nothing. As soon as a method has to build an object, read a value defined on the class, or stay correct under inheritance, cls is what is needed. Otherwise the static form is enough, and it states more clearly that the method depends on nothing.
Can it change a class attribute?
Yes, and that is its second common use: cls.setting = value changes the value for every instance that has no version of its own, which serves global settings and caches. Remember that the write lands on the class that was called.