In this tutorial we are going to talk about the python classmethod() function with examples.
Python classmethod() function is another built-in function that transforms a simple function or method into a class method.
It is similar to object method in Object Oriented Programming.
Syntax of classmethod() Function
The syntax of classmethod() function in Python is shown below –
Since it is considered un-pythonic way, we can use @classmethod decorator for classmethod definition.
Syntax is –
@classmethod def func(cls, args...)
class C: @classmethod def f(cls, arg1, arg2, ...):
Here, we created a function f() in class C. Decorator @classmethod helps us to convert defined method f() into class method.
Parameters of classmethod() Function
classmethod() function takes only one parameter –
- Function that needs to be converted into class method
Return type of classmethod() Function
The return type of the classmethod() function is a method that can be applied to class.
Examples of classmethod() Function
class Greeting: @classmethod def hello(cls): return "Hello Tutorialwing!" print(Greeting.hello())
In the above example, we are trying to create a classmethod named hello(). So, first of all we created a class named Greeting. Inside this class, we defined a function named hello() that returns ‘Hello Tutorialwing!’ when called. Using decorator @classmethod enabled us to call method hello() with class name.
import random class House : @classmethod def color(cls) : colors = ["red", "yellow", "green", "blue"] return random.choice(colors) print(House.color())
In this case, we created a class named House and a class method named color(…) that returns color of the house at random from the list of colors ([“red”, “yellow”, “green”, “blue”]).
class User: @classmethod def username(cls, name): return name print(User.username("Tutorialwing"))
In above example, notice that we creates a class method named username. This classmethod takes the name of user as positional argument and return it.
class FootballTeam: @classmethod def player(cls): return 11 print(FootballTeam.player())
In above python code, we are trying to display the number of player in a football team through the class method player().
class School: @classmethod def number_of_lessons(cls): return 7 print(School.number_of_lessons())
Here, we are displaying the number of lessons studied at school through the classmethod number_of_lessons().
Reference: Official Doc
Learn about more python examples at – https://tutorialwing.com/python-tutorial/
That’s end of this post on python classmethod() function with examples.