Register Login

@classmethod and @staticmethod Method in Python

Updated Feb 16, 2022

Classes play a significant role in the development of an object oriented Python program.

In this article, you will learn what are a class method and a static method, the difference between them, and when you can use them. As both methods require @classmethod and @staticmethod decorators you will initially get some understanding of decorators.

What are decorators?

Decorators are functions used to modify the behavior of an existing function. The decorator function takes a function as argument. They are very useful as they help to reuse the code. Decorators are called using @ keyword. Python has @classmethod and @staticmethod to define class method and static method respectively.

Example:

import time

#defining the decorator
def time_dec(func):
    def time_dec_args(*args, **kwargs):
        start=time.time()
        
        #calls cube(num) function
        result=func(*args, **kwargs)
        stop=time.time()
        
        #calculates the difference from the start time of decorator till end time of decorator execution
        print("time taken"+str(start-stop))

        #result has value 27
        return result
    return time_dec_args

#calling the decorator
@time_dec
def cube(num):
    res=num*num*num
    return res
    
print(cube(3))

Output:

Code Block

Consider the following code example as this will be used to understand class method and static method:

class Student:
    #class variable
    students_count = 0
  
     #class constructor
    def __init__(self, first_name, last_name, roll_no):
        self.first_name = first_name
        self.last_name = last_name
        self.roll_no = roll_no
        self.increment_student()
    
    #class method
    @classmethod
    def student_full_name(cls, full_name, roll_no):
        full_name = full_name
        return cls(full_name, '', roll_no)

     #class method
    @classmethod
    def increment_student(cls):
        cls.students_count += 1

     #static method
    @staticmethod
    def get_student_rules():
        rules = """
        1. Respect the teacher.
        2. Ask questions.
        """
        return rules


e1=Student('Aman', 'Gupta', 25)
print(e1.first_name)
print(e1.last_name)
print(e1.roll_no)
res=Student.student_full_name("a",30)
print(res.first_name)
print(res.last_name)
print(res.roll_no)

Output:

What is the class method?

A class method takes class (cls) itself as the first argument. A class method can only change the state of the Class but not the state of the Class object because Class objects cannot access the class methods, only the Class can directly access the class methods. It acts as an alternate constructor to the class.

For example, in the preceding code, generally the Student class object is created by providing three arguments first_name, last_name, and roll_no as shown in the following code:

s1 = Student('Aman', 'Gupta', 23)
print(s1.first_name)
print(s1.last_name)
print(s1.roll_no)

Output:

However, if the user only provides the first name, in this case our constructor will not work and here the class method,  student_full_name can help you as it will work as an alternative to Class constructor.

Example:

res=Student.student_full_name("a", 23)
print(res.first_name)
print(res.last_name)
print(res.roll_no)

Output:

Class methods are also used when we want to access only the class variables, for example , students_count in the above code which counts the total number of students.

e1=Student('Aman', 'Gupta', 25)
count=Student.students_count
print(f'Number of students: {count}')

res=Student.student_full_name("a",30)
count=Student.students_count
print(f'Number of students: {count}')

Output:

What are @staticmethod

Static methods are independent methods meaning they accept neither Class object nor Class itself as an argument, it does not work with instance variables nor with class variables. It can be accessed directly from the Class or from the Class object as shown in the following code block.

Example:

e1=Student('Aman', 'Gupta', 25)
#calling static method through Class object
print(e1.get_student_rules())

#calling static method through Class
print(Student.get_student_rules())

Output:

Difference between Staticmethod and Classmethod

Static Method Class Method

Static methods are defined using @staticmethod decorator.

Program:

@staticmethod
    def get_student_rules( ):

 

Class methods are defined using @classmethod decorator.

Program:

@classmethod
    def increment_student(cls):

 

It takes no arguments.

Example:

def get_student_rules( ):

 

It takes cls as the first argument.

Example:

def increment_student( cls, arg1, arg2, ....):

 

It does not modify the state of the class or Class object.

It modifies the state of the class.

Example:

@staticmethod
    def get_student_rules():
        rules = Respect the teacher.

        return rules

 

Example:

@classmethod
    def increment_student(cls):
        cls.students_count += 1

 

Which is better?

Static methods are better in terms of complexities as it is independent of Class or Class objects methods whereas Class methods take the class(cls) as an argument and change the state of the class which requires more time and space to process the execution as compared to static methods. They are also better because they as a whole are lightweight (because it does not leverage arguments) and faster compared to class methods.

Conclusion

We hope this article has given you a clear idea between static and class methods and how they are different from each other. Class methods can be used as an alternate Class constructor which modifies the state of the class.

Class methods are defined using @classmethod decorator and they are not accessed by Class objects. Static methods are independent functions and are defined using @staticmethod decorator but are not accessed either by Class or Class object.

Statically declared methods are faster and efficient compared to the class methods and static methods are mostly preferred by programmers for independent logic providing sections of the program.

Static methods are also lightweight because they do not entertain arguments, which reduce the extra baggage of executing parameter values from outside. Both these methods have unique use cases and programmers can leverage it for different purposes.


×