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"?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…