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
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- chr() in Python
- Python vs PHP
- pow() in Python
- Python Set | pop()
- gcd() in Python
- zip() in Python
- Python | a += b is not always a = a + b
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.