我只是不明白为什么我们需要使用@staticmethod。我们从一个例子开始。为什么我们使用@staticmethod?
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
在上面的例子中,该方法,static_add_one
,在两班不需要在计算中的类(个体)的实例。
该方法static_add_one
在类test1
装饰@staticmethod
和正常工作。
但在同一时间,在没有@staticmethod
装修也用了一招,它提供了论据一self
,但不会在所有使用它工作正常类test2
方法static_add_one
。
那么使用@staticmethod
有什么好处?它是否改善了性能?还是仅仅是由于python的禅宗说明“明确比隐含好”?
大多数情况下,只使用模块级别的函数并忘记存在'@ staticmethod'。 – roippi
让java程序员开心。 – michaelmeyer
@Ignacio Vazquez-Abrams:请问为什么我们不应该使用'test.static_add_one'? –