python中cls和self的不同

class A(object):
    a = 'a'
    @staticmethod
    def fool1(name):
        print(name)
    
    def fool2(self, name):
        print(name)  

    @classmethod 
    def fool3(cls, name):
         print(name)
    

首先定义了一个类A,类A中有3个函数,fool1是静态函数,用@staticmethod装饰器装饰,既可以有类名调用,也可以用类的实例调用:

a = A()
a.foo1('mamq') # 输出: hello mamq
A.foo1('mamq') # 输出: hello mamq

fool2是正常函数,是类的实例的函数,只能通过实例a调用:

a.foo2('mamq') # 输出: hello mamq
A.foo2('mamq') # 报错: unbound method foo2() must be called with A instance as first argument (got str instance instead)

fool3是类函数,cls作为第一个参数用来表示类本身,类方法只与类本身有关而与实例无关,如下两种方式都可以正常输出:

a.foo3('mamq') # 输出: hello mamq
A.foo3('mamq') # 输出: hello mamq

大家可以发现@staticmethod和@classmeithod的使用方法和输出完全相同,但两者仍存在区别。

classmethod中可以调用类中定义的其他方法、类的属性,但staticmethod只能通过A.a调用类的属性,但无法通过在该函数内部调用A.foo2()

class A(object):
    a = 'a'
    @staticmethod
    def foo1(name):
        print 'hello', name
        print A.a # 正常
        print A.foo2('mamq') # 报错: unbound method foo2() must be called with A instance as first argument (got str instance instead)
    def foo2(self, name):
        print 'hello', name
    @classmethod
    def foo3(cls, name):
        print 'hello', name
        print A.a
        print cls().foo2(name)

 

posted @ 2022-03-02 16:16  宇宙刘  阅读(146)  评论(0)    收藏  举报