@staticmethod 和 @classmethod,这两个 function decorator都是用来定义静态函数的。
相同点
调用这两个decorator定义的函数,都不用实例化类,直接用类名就可以调用
不同点
@classmethod 的第一个参数是 cls,因此可以访问类变量,或是用作类厂
而 @staticmethod 除了自身代码是位于类里面之外,对类的情况一无所知;@staticmethod 只适用于不想定义全局函数的情况
建议
一般情况下,尽量使用 @classmethod
Sample
class StaticClassMethodSample():
my_class_var = 3
@staticmethod
def my_staticmethod():
print StaticClassMethodSample.my_class_var
@classmethod
def my_classmethod(cls):
print cls.my_class_var
(原文地址: http://u50.cn/blog/python-staticmethod-%E5%92%8C-classmethod-%E7%9A%84%E5%BC%82%E5%90%8C)