-2

What i mean is what is the point of having staticmethods if normal methods can do the exact same thing? An example:

class test():
    _number = 0
    def change(number):
        test._number = number
    static_change = staticmethod(change)

test.change(10)
print(test._number)
test.static_change(10)
print(test._number)

I suppose it is to prevent the error that would pop up if the function was called from an instance instead of from the class itself?

Like this:

x = test()
test.change(10) #gives error
test.static_change(10) #doesn't give error
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • 1
    You are under no obligation to write static methods. I can't remember any occasion where I've felt inclined to use them. – khelwood Apr 12 '21 at 14:12
  • You can find some discussion of their uses and usefulness in https://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod – mercator Apr 12 '21 at 14:21
  • more like "uselessness" in this case. :-) – jsbueno Apr 12 '21 at 14:21
  • (also, when posting code here, beware of indentantion. Use the formatting button, or tripple backward quotes to separate your code. Your original post had the indentation wrong, and that is simply not valid Python. – jsbueno Apr 12 '21 at 14:23

1 Answers1

0

If you don't explictly need an static method, or are not in a project where this strict separation is needed, just do not use them.

In the case above, your "non static" method is wrong: regular methods will always receive an instance of the class when used as instance methods - your call would break if made from an instance.

So, if you need a method that just calculate something based on its input arguments, does not need any reference to the class, and no reference to the instance, it should be an static method.

Now, even if they do not need a reference to the instance and class, but will usually be called from an instance, they can just be regular methods (with an unused self first parameter).

And also, you should take care to see if it is worth writting the callable as an static method, if it makes sense for grouping purposes, or if it should be just a regular function. Since static methods cannot retrieve their related classes or instances, they can always be written as plain, module-level, functions. It is actually rare that it'd make more sense to have then as static methods (the only reason is for grouping purposes - a calculation that uses values typical present in an instance, but that should be passed as parameters rather than instance attributes, for example).

TL;DR: Unless you know exactly what you are doing, and it makes a little bit more sense to have an static method, you should not have an static method in Python code.

jsbueno
  • 99,910
  • 10
  • 151
  • 209