Python staticmethod() Function – Tutorial with Examples

The staticmethod() function in Python is a built-in function that is used to convert a method into a static method. A static method is a method that belongs to a class rather than an instance of the class. It does not receive any reference to the instance of the class and operates on the arguments passed to it.

Syntax

staticmethod(function)

Parameters

  • function : The method that needs to be converted to a static method.

Return Value

The staticmethod() function returns the input function as a static method. The function can be called using the class name rather than an instance of the class.

Examples

Example 1: Converting a method to a static method

# Converting a method to a static method
class Example:
    @staticmethod
    def static_method(x, y):
        return x + y
print(Example.static_method(3, 4))

Output

7

Example 2: Using a static method as a utility function

# Using a static method as a utility function
class Example:
    @staticmethod
    def is_even(n):
        return n % 2 == 0
print(Example.is_even(4))
print(Example.is_even(5))

Output

True
False

Example 3: Using a static method with inheritance

# Using a static method with inheritance
class Parent:
    @staticmethod
    def static_method(x, y):
        return x + y
class Child(Parent):
pass

print(Child.static_method(3, 4))

Output

7

Use Cases

The staticmethod() function is often used in the following scenarios:

  • As a utility function that does not operate on the instance of the class.
  • As a method that can be called directly on the class name, rather than an instance of the class.
  • To improve code organization by separating functions that do not operate on the instance of the class into their own class as static methods.

Conclusion

In conclusion, the staticmethod() function in Python is a useful tool for converting a method into a static method. Static methods do not receive any reference to the instance of the class and can be called directly on the class name. It is often used as a utility function or to improve code organization. With the understanding of the syntax, return value and examples discussed in this article, you can easily use the staticmethod() function in your own Python code.

Leave a Reply

Your email address will not be published. Required fields are marked *