Let’s understand the static method and class method in python one by one then we will compare the difference between them.

Recommended:

Static Method in Python

To Declare a static method we need to attach ‘@staticmethod‘ decorator before the function declaration.

In Static methods, neither self(object instance) nor cls(class reference) is passed as argument. So it behaves as normal function except the fact it can be called using class or object reference.

Python Example of Static Method

Tip: Use static method when you don’t need to use class variables inside it to perform a particular task.

Class Method in Python

To declare class method, we need to attach ‘@classmethod‘ decorator before the function declaration.

In class method, cls is passed as an argument although we can call this method using object or class reference.

Python Example of Class Method

Tip: Use class method when you want to access the class variable inside the function or for any other use of class reference like creating another object inside the function.

Hope, now you know the difference between static method and class method and will able to use it whenever required in your program. If you have any doubts then comment below.

Leave a Reply

Close Menu