Javatpoint Logo
Javatpoint Logo

Classmethod() in Python

Python has a built-in function called classmethod() that gives a class method of the specified function.;

Syntax:

Parameter: This method accepts the name of the function as its parameter.

Return Type: This method returns the function converted to a class method.

We can also use the decorator form @classmethod for defining the classmethod.

Syntax:

Where,

function: this is the function that is required to be converted to a class method

returns: the converted class method of the function.

Instead of being tied to an instance, classmethod() functions are attached to classes. Both classes and objects are capable of calling class methods. Both classes and objects can be used to invoke these methods.

Class method vs. Static Method

Although a static method requires no particular arguments, a class method accepts cls as its first argument.

Though a static method cannot access or alter the class state, a class method may.

Static methods are typically unaware of the class state. They are utility methods that operate on some parameters after receiving them. On the other hand, the class must be a parameter for class methods.

Python's @classmethod decorator and @staticmethod decorator are used to generate class and static methods, respectively.

Examples of classmethod in Python

This example will show how to create a simple classmethod.

In this illustration, we'll learn how to construct a class method. To do this, we made a class called Python with a variable called the course and a method called algo that prints the object that is passed to it.

We then called the class function algo without constructing a function object after passing the method Python.algo into the classmethod, which transforms the method into the class method.

Code

Output

This is an algorithm:  Algorithm

Creating a class method using the classmethod() function

Code

Output

The given name is:  Javatpoint

Factory Method Using Class Method

Factory design patterns use the classmethod() function when invoking several functions using the class name instead of the object.

Code

Output

22
24
True






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA