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 | Functions | Question 4
- Python | Functions | Question 5
- Python | Functions | Question 6
- Python lambda (Anonymous Functions) | filter, map, reduce
- *args and **kwargs in Python
- join() function in Python
- Python reversed() function
- Python | startswith() and endswith() functions
- Python | fsum() function
- Python __iter__() and __next__() | Converting an object into an iterator
- Monkey Patching in Python (Dynamic Behavior)
- Python | tuple() Function
- Difference between Method and Function in Python
- Python | TextBlob.word_counts() method
- Python Number | uniform() method
- Python Number | fabs() method
- Python Strings encode() method
- Python Strings decode() method
- Python 3 Strings | expandtabs() method
- Default arguments 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.
Improved By : yegoun98