classmethod() is an inbuilt function in Python, which returns a class method for a given function.
Parameter :This function accepts the function name as a parameter.
Return Type:This function returns the converted class method.
classmethod() methods are bound to a class rather than an object. Class methods can be called by both class and object. These methods can be called with a class or with an object. The examples below clearly illustrate this.
The name is : Geeksforgeeks
My favorite_subject_name is : Networking
Uses of classmethod() classmethod() function is used in factory design patterns where we want to call many functions with the class name rather than object.
@classmethod decorator, is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition.
A class method receives the class as the implicit first argument, just like an instance method receives the instance.
class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: the function that needs to be converted into a class method returns: a class method for function.
- A class method is a method which is bound to the class and not the object of the class.
- They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
- It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that would be applicable to all the instances.
In the below example we use a
classmethod() to check if a person is an adult or not.
21 22 True
- Python - Read blob object in python using wand library
- Python | PRAW - Python Reddit API Wrapper
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- MySQL-Connector-Python module in Python
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Visualizing O(n) using Python
- gcd() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : yegoun98