python 对象方法 classmethod, staticclassmethod 区别

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

你可能感兴趣的:(python 对象方法 classmethod, staticclassmethod 区别)