I just don’t understand why we need to use @staticmethod. Start with an example.
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)
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)
In the above example, a method static_add_onein two classes does not require an instance of the class (self) in the calculation.
The method static_add_onein the class test1is decorated @staticmethodand works correctly.
But at the same time, a method static_add_onein a class test2that has no decoration @staticmethodalso works correctly, using a trick that provides an argument selfin the argument, but does not use it in everything.
So what is the advantage of using @staticmethod? Does performance improve? Or is it simply because of zen python that states that “Explicit is better than implicit”?