Python staticmethod() Function
The Python staticmethod() function is a built-in function used to convert a given method into a static method. Once the method is converted, it is not bound to an instance of the class but to the class itself.
Like other object-oriented programming languages, Python also has the concept of static methods. This type of methods can be invoked directly without creating an instance of the class.
Syntax
Following is the syntax of the Python staticmethod() function β
staticmethod(nameOfMethod)
Parameters
The Python staticmethod() function accepts a single parameter β
nameOfMethod β This parameter represents a method that we want to convert into static.
Return Value
The Python staticmethod() function returns a static method.
staticmethod() Function Examples
Practice the following examples to understand the use of staticmethod() function in Python:
Example: Use of staticmethod() Method
The following example shows the usage of Python staticmethod() function. Here, we are creating a method that perform addition of two numbers. And then, we are passing this method along with the class name to the staticmethod() as a parameter value to convert it into a static method.
class Mathematics:
def addition(valOne, valTwo):
return valOne + valTwo
Mathematics.addition = staticmethod(Mathematics.addition)
output = Mathematics.addition(51, 99)
print("The result of adding both numbers:", output)
When we run above program, it produces following result β
The result of adding both numbers: 150
Example: Define Static Method Using @staticmethod Decorator
To define a static method, Python provides another way which is the use of @staticmethod decorator. Below is an example of creating a static method named "subtraction".
class Mathematics:
@staticmethod
def subtraction(valOne, valTwo):
return valOne - valTwo
output = Mathematics.subtraction(99, 55)
print("The result of subtracting both numbers:", output)
Following is an output of the above code β
The result of subtracting both numbers: 44
Example: Use of staticmethod() With Utility Functions
In Python, one of the use-case of staticmethod() is the utility functions which are a way of implementing common tasks that can be frequently reused. The code below demonstrates how to use the staticmethod() with the utility functions.
class Checker:
@staticmethod
def checking(value):
return isinstance(value, int)
print("Is the given number is integer:")
print(Checker.checking(142))
Output of the above code is as follows β
Is the given number is integer: True