classmethod() is an inbuilt function in Python which returns a class method for given function.
Parameter :This function accept function name as parameter.
Return Type:This function returns converted class method.
classmethod() methods are bound to class rather than an object. Class methods can be called by both class and object. These methods can be call with class or with object. Below examples illustrates above clearly.
The name is : Geeksforgeeks
My favorite_subject_name is : Networking
Uses of classmethod() classmethod() function is used in factory design pattern where we want to call many functions with the class name rather than object.
@classmethod decorator, is a builtin function decorator that 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 implicit first argument, just like an instance method receives the instance.
class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: 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 will be applicable to all the instances.
In the below example we use a
classmethod() to check if a person is adult or not.
21 22 True
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- Python | a += b is not always a = a + b
- Any & All in Python
- SQL using Python | Set 1
- chr() 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 firstname.lastname@example.org. 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.