Python中的classmethod與staticmethod

來源:互聯網
上載者:User

標籤:訪問   object   python   使用   問題   self   div   第一個   print   

首先,這是一個經典的問題。

我們首先做一個比較:

classmethod的第一個參數是cls,即調用的時候要把類傳入

這意味著我們我們可以在classmethod裡使用類的屬性,而不是類的執行個體的屬性(顯式建立可用)

staticmethod,調用的時候沒有參數,即調用的時候我們不傳入東西(類,類的執行個體)

這意味著我們在staticmethod裡無法得到類的執行個體(顯式建立可用)

而我們調用類的普通方法的時候,要把self傳進去

這意味著在這個普通方法裡,我們只能使用類的執行個體(self)的屬性方法

至於怎麼調用呢?看下面:

class A(object):      bar = 1      def foo(self):          print ‘foo‘       @staticmethod      def static_foo():          print ‘static_foo‘          print A.bar    # static_foo位於class A中,A相當於全域的,所以能訪問到A的屬性      A().foo() # static_foo位於class A中,A相當於全域的,所以能訪問到A的方法
    @classmethod      def class_foo(cls):          print ‘class_foo‘          print cls.bar  # 等於調用 A.bar        cls().foo()     # 等於調用 A().foo()  A.static_foo()  A.class_foo()  

輸出:

static_foo, 1,foo

class_foo,1,foo

一目瞭然

 

Python中的classmethod與staticmethod

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.