Python Forum

Full Version: Using static methods for library?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody,

I need to create a library of algorithms. I do no want to instanciate an object of the class everytime, i just would like to call the algorithm.

I.e. My class is called "algorithms", i would like to call algorithms.shortestPath(input).

What's the Pythonic way of doing this? I could create a class with only static methods, would that be a good solution?

Thanks
Is there a reason for it not to just be a function? Is there any state that needs to be maintained. You could use static functions of a class but if all you need is a function, a function is what you should write.
No, i do not need to mantain any state. I need an algorithm.py to have some algorithms that i can call from another file. Would you mind giving a little example on how you would structure the algorithm.py file?

Thanks
Just functions in algorithm.py:
def alg1():
    print("In alg 1.")


def alg2():
    print("In alg 2.")
Import and call in some other file:
import algorithm


algorithm.alg1()

algorithm.alg2()
Output:
In alg 1. In alg 2.
Perfect, that looks like what i was looking for. Thanks