create a static function in python

To create a static function in Python, you can use the @staticmethod decorator. A static method does not require an instance of the class to be called and can be called directly from the class. Here is an example:

main.py
class MyClass:
    @staticmethod
    def my_static_method():
        print("This is a static method.")

# Calling the static method directly from the class
MyClass.my_static_method() # Output: "This is a static method."

# Creating an instance of the class and trying to call the static method
obj = MyClass()
obj.my_static_method() # Output: "This is a static method."
370 chars
12 lines

As you can see in the example above, the @staticmethod decorator is used to define a static method my_static_method() inside the MyClass class. The static method can be called directly from the class MyClass without the need for an instance of the class. If an instance of the class is created, the static method can still be called from the instance as well.

gistlibby LogSnag