![]() |
VOOZH | about |
@classmethod is used to create a method that works with the class instead of an object instance. A class method receives the class itself as the first argument using cls. It is commonly used to access class variables, create factory methods and perform operations related to the class.
Example: In this example, a class method is used to access a class variable without creating an object.
Python
Explanation: @classmethod converts show_course() into a class method, and cls.course accesses the class variable course.
class ClassName:
@classmethod
def method_name(cls, args):
# method body
Parameters:
Return Value: Returns a class method object.
Example 1: In this example, the class method accesses and prints a class variable shared by all objects.
Toyota
Explanation: cls.brand accesses the class variable brand directly using the class method.
Example 2: In this example, a class method creates an object using a formatted string.
Alex 21
Explanation: from_string() uses cls() to create and return a new object from the string data.
Example 3: In this example, classmethod() function is used directly instead of the @classmethod decorator.
GeeksforGeeks
Explanation: classmethod(Demo.show) converts the normal method show() into a class method.