示例代码如下:
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()
代码调用执行如下:
a.foo(1)
# executing foo(<
__main__.A
object at 0xb7dbef0c>,1)
-----------------------------------------------------------------
a.class_foo(1)
# executing class_foo(<
class
'__main__.A'>,1)
A.class_foo(1)
# executing class_foo(<
class
'__main__.A'>,1)
-----------------------------------------------------------------
a.static_foo(1)
# executing static_foo(1)
A.static_foo('hi')
# executing static_foo(hi
区别:
A、foo()的调用者必须是类A的一个实例,class_fool()与static_foo()的调用者既可以是类也可以是某个实例;
B、参数不同,foo()参数为self和其他参数,class_foo()参数使用类(cls)替换self,static_foo()则只有参数,没有self和类(cls);
C、a.foo(1)中的foo()与a绑定,class_foo()是与类绑定的,而static_fool与这两者没有绑定;
class A(object): def foo(self): print "executing foo(%s,%s)" @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() print a.foo() print a.class_foo(1) print a.static_foo(1) print A.foo(a) print A.static_foo(1) print A.class_foo(1)