Static method belongs to a class and not to an object. It does not take self
and cls
as a parameter. Static method cannot access instance variables and instance methods of a class. Static methods work like regular functions. And mainly used as utility functions. Outside the class, static methods can be accessed using objects and classname as shown below-
obj.methodName() OR ClassName.methodName()
There are two ways of creating static methods-
@staticmethod
decoratorstaticmethod()
methodIt is the most preferred way of creating static methods. It has the following syntax-
@staticmethod def functionName(arg1, arg2, ...): #function body
class Math: @staticmethod def add(p1, p2): return p1+p2 print('Sum of 23 and 54 is', Math.add(23, 54))
Output of the above program
Sum of 23 and 54 is 77
Note: Using the below syntax, you can call other class and static methods from class method-
cls.MethodName() OR ClassName.MethodName()
staticmethod()
is used to convert a regular method to a static method.
class Math: def add(p1, p2): return p1+p2 #creating add static method Math.add = staticmethod(Math.add) print('Sum of 23 and 54 is', Math.add(23, 54))
Output of the above program
Sum of 23 and 54 is 77