Python – Why Use @staticmethod

python

I just can't see why do we need to use @staticmethod. Let's start with an exmaple.

class test1:
    def __init__(self,value):
        self.value=value

    @staticmethod
    def static_add_one(value):
        return value+1

    @property
    def new_val(self):
        self.value=self.static_add_one(self.value)
        return self.value


a=test1(3)
print(a.new_val) ## >>> 4



class test2:
    def __init__(self,value):
        self.value=value

    def static_add_one(self,value):
        return value+1

    @property
    def new_val(self):
        self.value=self.static_add_one(self.value)
        return self.value


b=test2(3)
print(b.new_val) ## >>> 4

In the example above, the method, static_add_one , in the two classes do not require the instance of the class(self) in calculation.

The method static_add_one in the class test1 is decorated by @staticmethod and work properly.

But at the same time, the method static_add_one in the class test2 which has no @staticmethod decoration also works properly by using a trick that provides a self in the argument but doesn't use it at all.

So what is the benefit of using @staticmethod? Does it improve the performance? Or is it just due to the zen of python which states that "Explicit is better than implicit"?

Best Answer

The reason to use staticmethod is if you have something that could be written as a standalone function (not part of any class), but you want to keep it within the class because it's somehow semantically related to the class. (For instance, it could be a function that doesn't require any information from the class, but whose behavior is specific to the class, so that subclasses might want to override it.) In many cases, it could make just as much sense to write something as a standalone function instead of a staticmethod.

Your example isn't really the same. A key difference is that, even though you don't use self, you still need an instance to call static_add_one --- you can't call it directly on the class with test2.static_add_one(1). So there is a genuine difference in behavior there. The most serious "rival" to a staticmethod isn't a regular method that ignores self, but a standalone function.

Related Question