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.

Examples

In this section, we will see some examples of staticmethod() function −

Example 1

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 2

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 3

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
python_built_in_functions.htm
Advertisements