您的位置:首页 > 编程语言 > Python开发

python 对象方法 classmethod, staticclassmethod 区别

2014-03-04 14:56 330 查看

python 中普通方法,classmethod, staticclassmethod

class A(object):
'''
这个地方定义的变量为cls区域的
'''
a1=1
a2=2
def foo(self,x):
'''
对象方法有self, 这个地方定义是obj区域的
'''
self.a1=50
self.a2=30
print "executing foo(%s,%s)"%(self,x), "self scope", self.a1, "cls scope", A.a1

@classmethod
def class_foo(cls,x):
'''
类方法有cls
'''
print "executing class_foo(%s,%s)"%(cls,x)

@staticmethod
def static_foo(x):
'''
静态方法很懒,什么都没有
'''
print "executing static_foo(%s)"%x

a=A()
a.foo(1)
A.class_foo(1)
A.static_foo(22)

运行看看结果:

executing foo(<__main__.A object at 0x10efd82d0>,1)  self scope:  50  cls scope:  1
executing class_foo(<class '__main__.A'>,1)
executing static_foo(22) 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: