add a static method to a class in python

To add a static method to a class in Python, you can use the staticmethod built-in function. A static method belongs to a class rather than an instance of the class, and can be called without creating an object of the class.

Here's an example:

main.py
class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2):
        # do something
        return result
116 chars
6 lines

In this example, my_static_method() is defined as a static method of the MyClass class using the @staticmethod decorator. Any arguments that are passed to the method are passed explicitly, without the self argument that is passed to instance methods.

To call a static method, you can use the class name followed by the method name:

main.py
result = MyClass.my_static_method(arg1, arg2)
46 chars
2 lines

Note that a static method does not have access to the instance or class state, and cannot modify any attributes or call any other methods that are not also static.

gistlibby LogSnag