Updated September 29, 2023
Introduction to classmethod() in Python
To use the Class Method in Python, We have to use the Class method decorator ‘@classmethod’. You define the class method decorator just before the function definition. Class is passed in the function as a parameter and should be the first parameter. We use the ‘cls’ keyword for passing to the function. Cls denotes that the class is passed as a variable. This is done to modify the class variable and objects, as everything is an object in Python.
Syntax:
class anyName:
@classmethod
def methodName(cls, arg1,arg2 ….):
----
----
(lines of code)
How classmethod() Work in Python?
The class method has only access to the parameters of the class and arguments. The class method doesn’t have self-arguments, so it can only access the class itself and the object representing it. When we create an instance of the class and call the class method, we won’t be able to access the self-object; it can only access the class’s attributes.
We recommend using class methods when working on factory methods because they return the class object. Class method decorator allows us to call functions within classes without instantiating them. While using the class method, please note that it receives the lowest class of the calling subject, which might have implications when trying to update the class’s data through the passed class.
We can see that the class method always implements the lowest in the instance tree. A class method is best suited when processing data that might differ for each class in the hierarchy.
Examples to Implement classmethod() in Python
Below are the examples of classmethod in Python:
Example #1
Code:
class sampleclass():
def __init__(self, name):
self.studentname = name
@classmethod
def squareroot(cls, number):
sampleclass.result = number * number
sampleclass.squareroot(5)
print(sampleclass.result)
Output:
The above program calculates the square root of the number. We have created the class ‘sampleclass’ and defined a constructor inside it. We have defined the class method decorator before the method. We have created a method, ‘squareroot’; the first parameter is the cls, which denotes the class and passed number parameter. We have also created a class-level variable, ‘result’ that stores the output.
Now you can call the method using classname.methodname and pass the parameter.
Example #2
Code:
class Car:
def __init__(self, features):
self.features = features
def __repr__(self):
return f'Car({self.features})'
@classmethod
def audi(cls):
return cls(['ABS', 'Disk Brakes'])
@classmethod
def mercedes(cls):
return cls(['ABS', 'Disk Brakes', 'GPS', 'Alloy Wheels'])
print(Car.audi())
print(Car.mercedes())
Output:
In the above program, we have created a class ‘Car’ and defined a constructor. We have defined two-class methods, ‘audi’ and ‘mercedes’, and we have created instances of the class. These values will be returned when we will call our class method. We can call our Audi and Mercedes classes by just calling Car class; we don’t need to pass any instance.
Example #3
Code:
class Organisation:
intern = 0
increment = 10000
def __init__(self, firstname, lastname, salary):
self.firstname = firstname
self.lastname = lastname
self.salary = salary
@classmethod
def set_increment(cls, amount):
cls.increment = amount
emp_1 = Organisation('Corey', 'Schafer', 50000)
emp_2 = Organisation('Test', 'Organisation', 60000)
Organisation.set_increment(15000)
print(Organisation.increment)
print(emp_1.increment)
print(emp_2.increment)
Output:
In the above program, we created a class Organisation and two variables, intern and increment. We have defined a self-constructor that takes 3 parameters. We have defined our class method, created class variable increment, and assigned the amount argument we passed along with cls.
We have created two organizational instances. Now we comment ‘Organisation.set_increment(15000)’ in the line, then we get the output as 10000 for all three print commands as we have already assigned 10,000 at the class level. Now we call the Organisation class and call our class method, i.e., set_increment. So we are going the amount in the class method, and now if we run it, all of the output will be 15000. It happened because we ran the set_increment method, i.e., class method, which means now we are working with class instead of instance, and we are setting that class variable raise amount equal to the amount we have passed here.
We can also run a class method using an instance, but that doesn’t make sense and is not a good practice. We can use the class method as an alternative constructor and provide multiple ways of creating objects.
Conclusion
The class method is very useful for creating code, and managing code is very easy; we don’t need to change everywhere in the code. Creating an API with a classmethod is very easy. The Best use of the class method is when we are making too many methods and want to call those methods using class, not objects.
Recommended Articles
We hope that this EDUCBA information on “classmethod() in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.