Python built-in Method - staticmethod()

http‮/:s‬/www.theitroad.com

The staticmethod() is a built-in method in Python that is used to define a static method for a class. A static method is a method that belongs to a class rather than to an instance of the class. This means that a static method can be called on the class itself, rather than on an instance of the class.

The staticmethod() method takes a single parameter, which is the method that you want to make static. Here is the syntax for the staticmethod() method:

class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2, ...):
        # method body

To define a static method in a class, you use the @staticmethod decorator before the method definition. The @staticmethod decorator tells Python that the following method is a static method.

Here is an example of how to use the staticmethod() method in a class:

class MyClass:
    @staticmethod
    def my_static_method(x, y):
        return x + y

print(MyClass.my_static_method(3, 4))

In this example, we define a class MyClass that has a static method my_static_method(). The my_static_method() method takes two arguments x and y, and returns their sum. We can call the my_static_method() method on the class MyClass itself, rather than on an instance of the class, by using the class name followed by the method name, as shown in the print() statement.

The output of the above code will be 7.

Static methods are useful when you need to define a method that belongs to a class rather than to an instance of the class, and does not require any information from the instance. Static methods can be called on the class itself, rather than on an instance of the class, making them more convenient to use in some cases.