Python staticmethod Decorator - @staticmethod
The static method decorator or @staticmethod is used to define methods inside a class as static methods. For example:
class CodesCracker: @staticmethod def statfun(x): print("Value of x:", x) CodesCracker.statfun("Hey!")
Here is its output:
Value of x: Hey!
Note - Static methods do not have access to what the class is. The static method is just a function, without having access to the object of the class (where the static method is defined) and its internals. The differentiation between these two is provided in class method Vs static method in Python.
Note - Also there is no any self or cls parameter for static method. When we need to define a normal static method inside a class, that can call directly using the class, we need @staticmethod decorator to do the task.
Python @staticmethod Decorator Syntax
The syntax of @staticmethod decorator in Python is given below:
@staticmethod def myfun(arg1, arg2, arg3, ..., argN): # definition code goes here
Python @staticmethod Decorator Example
Here is a simple example of @staticmethod decorator in Python. This program uses the @staticmethod to define static methods inside a class named CodesCracker:
class CodesCracker: @staticmethod def myfun(a, b, c, s): print("The value of a:", a) print("The value of b:", b) print("The value of c:", c) print("The value of s:", s) CodesCracker.myfun(100, 200, 300, "Python is Fun!")
The sample output produced by this Python program, is shown in the snapshot given below:
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube