classmethod()

dakshdeepHERE's avatar
Published Jul 6, 2021Updated Jul 5, 2023
Contribute to Docs

Converts a given function into a class method.

Syntax

classmethod(function)

Example 1

Use classmethod() to create the Codecademy class method:

class Student:
name = "Codecademy"
def print_name(obj):
print("Welcome to...", obj.name)
Student.print_name = classmethod(Student.print_name)
Student.print_name()

Codebyte Example

Here’s an example to illustrate the usage of classmethod():

Code
Output
Loading...

Output for the above code is:

Instance method called by Object 1
Class method called. Total instances created: 2
Class method called. Total instances created: 2
Class method called. Total instances created: 2

In the above example, a class called MyClass is defined with a class attribute count and two methods: instance_method and class_method.

The instance_method is a regular instance method that can access instance-specific attributes. It is called using an instance of the class.

The class_method is a class method decorated with classmethod(). It takes the class itself (cls) as the first parameter instead of the instance (self). It can access and modify class-level attributes, such as count. It can be called using the class name or an instance of the class.

All contributors

Contribute to Docs

Learn Python on Codecademy