Skip to main content

staticmethod()

The staticmethod() function in Python returns a static method for a given function. Static methods are bound to the class rather than an instance of the class, and they do not have access to self or cls attributes. This function is typically used as a decorator to define a static method within a class.

Parameter Values

Parameter Description
function

A function that is converted to a static method. The function does not receive an implicit first argument.

Return Values

The staticmethod() function returns a static method for a given function.

How to Use staticmethod() in Python

Example 1:

Converts a function into a static method. A static method does not receive an implicit first argument (usually self or cls). It can be called both on the class and on an instance of the class.

class MyClass:
    @staticmethod
    def static_method():
        return 'This is a static method'

print(MyClass.static_method())

obj = MyClass()
print(obj.static_method())
Example 2:

Allows the static method to be called from the class itself without needing to create an instance.

class MathOperations:
    @staticmethod
    def add(x, y):
        return x + y

print(MathOperations.add(5, 3))
Example 3:

Typically used when the method does not depend on any particular instance of the class and can be logically grouped within the class for organization purposes.

class StringUtils:
    @staticmethod
    def is_palindrome(s):
        return s == s[::-1]

print(StringUtils.is_palindrome('radar'))