@staticmethod和@classmethod

Python其实有3个方法,即静态方法(staticmethod),类方法(classmethod)和实例方法,如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# 普通方法
def foo(x):
    print "executing foo(%s)"%(x)

class A(object):
    # 实例方法
    def foo(self,x):
        print "executing foo(%s,%s)"%(self,x)
    # 类方法
    @classmethod
    def class_foo(cls,x):
        print "executing class_foo(%s,%s)"%(cls,x)
    # 静态方法
    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)"%x

a=A()

self代表实例,cls代表类,实例方法和类方法的使用类似于一个偏函数(partical function),他们的第一个参数已经被固定的绑定为实例和类。静态方法更像是一个普通函数,他不绑定任何东西,他的出现或许仅仅是代码的风格问题,它允许你将一个普通函数绑定写到类的定义里面,假想你在写一个模块,里面有若干个类,但是需要一些普通函数来完成一些辅助工作,如果这个普通函数只是为了服务某个类,那么我们没有必要单独全局定义它,反而使用@staticmethod会让代码更加简洁优雅。

实例方法 类方法 静态方法
a.foo(x) a.class_foo(x) a.static_foo(x)
不可用 A.class_foo(x) A.static_foo(x)

注:使用a.clss_foo(x)时系统会自动查找a所对应的类 更多关于这个问题:

http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python https://realpython.com/blog/python/instance-class-and-static-methods-demystified/