装饰的功能@staticmethod和装饰的功能有什么区别@classmethod?
以下类方法有什么区别?
是一个是静态而另一个不是?
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
Run Code Online (Sandbox Code Playgroud) 我只是不明白为什么我们需要使用@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
Run Code Online (Sandbox Code Playgroud)
在上面的示例static_add_one中,两个类中的方法在计算中不需要类(self)的实例.
该方法static_add_one在类test1是由装饰@staticmethod和正常工作.
但与此同时,static_add_one类test2中没有@staticmethod装饰的方法也可以通过使用self在参数中提供但完全不使用它的技巧来正常工作.
那么使用的好处是@staticmethod什么?它会改善性能吗?或者仅仅是因为python的禅宗指出" 明确比隐含更好 "?
我对python很陌生,无法理解python中的静态方法是什么(例如__new__())以及它有什么作用。谁能解释一下?太感谢了