Static Methods in Python

In Python, static methods are defined within a class using the @staticmethod decorator. They do not require a class instance or the self parameter to be invoked. Static methods can be called on the class itself or on an instance of the class, and they are generally used for utility functions that perform a task in isolation from class attributes or methods.

Key Features of Static Methods:

Example of Static Method in Python

This example demonstrates the use of a static method within a Python class.

Code Example

class MathOperations:
            @staticmethod
            def add(x, y):
                return x + y
        
            @staticmethod
            def multiply(x, y):
                return x * y
        
        # Calling static methods using the class name
        sum_result = MathOperations.add(10, 5)
        product_result = MathOperations.multiply(10, 5)
        
        # Displaying the results
        print("Sum:", sum_result)
        print("Product:", product_result)
        

Output

Sum: 15
Product: 50

Conclusion

Static methods are a powerful feature in Python that allows for the organization of related functions within a class. They provide a way to encapsulate functions that logically belong to a class without needing to instantiate an object, promoting code organization and reusability.