python中的cls到底指的是什么,與self有什么區別?


一般來說,要使用某個類的方法,需要先實例化一個對象再調用方法。

而使用@staticmethod或@classmethod,就可以不需要實例化,直接類名.方法名()來調用。

這有利於組織代碼,把某些應該屬於某個類的函數給放到那個類里去,同時有利於命名空間的整潔。

  1.  
    class A(object):
  2.  
    a = 'a'
  3.  
    @staticmethod
  4.  
    def foo1(name):
  5.  
    print 'hello', name
  6.  
    def foo2(self, name):
  7.  
    print 'hello', name
  8.  
    @classmethod
  9.  
    def foo3(cls, name):
  10.  
    print 'hello', name

首先定義一個類A,類A中有三個函數,foo1為靜態函數,用@staticmethod裝飾器裝飾,這種方法與類有某種關系但不需要使用到實例或者類來參與。如下兩種方法都可以正常輸出,也就是說既可以作為類的方法使用,也可以作為類的實例的方法使用。

  1.  
    a = A()
  2.  
    a.foo1( 'mamq') # 輸出: hello mamq
  3.  
    A.foo1( 'mamq')# 輸出: hello mamq

foo2為正常的函數,是類的實例的函數,只能通過a調用。

  1.  
    a.foo2( 'mamq') # 輸出: hello mamq
  2.  
    A.foo2( 'mamq') # 報錯: unbound method foo2() must be called with A instance as first argument (got str instance instead)

foo3為類函數,cls作為第一個參數用來表示類本身. 在類方法中用到,類方法是只與類本身有關而與實例無關的方法。如下兩種方法都可以正常輸出。

  1.  
    a.foo3( 'mamq') # 輸出: hello mamq
  2.  
    A.foo3( 'mamq') # 輸出: hello mamq

但是通過例子發現staticmethod與classmethod的使用方法和輸出結果相同,再看看這兩種方法的區別。

既然@staticmethod和@classmethod都可以直接類名.方法名()來調用,那他們有什么區別呢
從它們的使用上來看,
@staticmethod不需要表示自身對象的self和自身類的cls參數,就跟使用函數一樣。
@classmethod也不需要self參數,但第一個參數需要是表示自身類的cls參數。
如果在@staticmethod中要調用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
而@classmethod因為持有cls參數,可以來調用類的屬性,類的方法,實例化對象等,避免硬編碼。

也就是說在classmethod中可以調用類中定義的其他方法、類的屬性,但staticmethod只能通過A.a調用類的屬性,但無法通過在該函數內部調用A.foo2()。修改上面的代碼加以說明:

  1.  
    class A(object):
  2.  
    a = 'a'
  3.  
    @staticmethod
  4.  
    def foo1(name):
  5.  
    print 'hello', name
  6.  
    print A.a # 正常
  7.  
    print A.foo2('mamq') # 報錯: unbound method foo2() must be called with A instance as first argument (got str instance instead)
  8.  
    def foo2(self, name):
  9.  
    print 'hello', name
  10.  
    @classmethod
  11.  
    def foo3(cls, name):
  12.  
    print 'hello', name
  13.  
    print A.a
  14.  
    print cls().foo2(name)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM