Python classmethod()
Anonymous contributor
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():
Output for the above code is:
Instance method called by Object 1Class method called. Total instances created: 2Class method called. Total instances created: 2Class 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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours