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


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. It behaves as normal function even for the object of the same class (since self parameter is not passed to this method), therefore inside static method we cannot access the class or instance variable 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 or instance 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 or self is passed as an argument although we can call this method using object or class reference.

When the class method is invoked through class name the class reference is passed automatically to the method, hence inside the method, we can access class variables.

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