A class method is a method that’s shared among all objects. To call a class method, put the class as the first argument.

Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.

Related course: Complete Python Programming Course & Exercises

Example

Classmethod example

To turn a method into a classmethod, add @classmethod before the method definition. As parameter the method always takes the class.

The example below defines a class method. The class method can then be used by the class itself. In this example the class method uses the class property name.

1
2
3
4
5
6
7
8
class Fruit:
name = 'Fruitas'

@classmethod
def printName(cls):
print('The name is:', cls.name)

Fruit.printName()

You can use a classmethod with both objects and the class:

1
2
3
4
5
6
apple = Fruit()
berry = Fruit()

Fruit.printName()
apple.printName()
berry.printName()

The parameter name now belongs to the class, if you’d change the name by using an object it ignores that. But if you’d do that by the class it changes, example below:

1
2
3
4
5
6
7
8
9
apple.name="Apple"
Fruit.printName()
apple.printName()
berry.printName()

Fruit.name="Apple"
Fruit.printName()
apple.printName()
berry.printName()

Alternative writing

Often the pythonic notation is used, but this is not strictly required.
You can also use a classmethod like this:

1
2
3
4
5
6
7
8
class Fruit:
name = 'Fruitas'

def printName(cls):
print('The name is:', cls.name)

Fruit.printAge = classmethod(Fruit.printName)
Fruit.printAge()

classmethod vs staticmethod

Like a static method, a class method doesn’t need an object to be instantiated.

A class method differs from a static method in that a static method doesn’t know about the class itself. In a classmethod, the parameter is always the class itself.

a static method knows nothing about the class or instance. You can just as well use a function call.

a class method gets the class when the method is called. It knows abouts the classes attributes and methods.

If you are a beginner, then I highly recommend this book.

Exercises

Exercises for classmethod article:

  • What is a classmethod?
  • How does a classmethod differ from a staticmethod?

Download examples