[Python小菜]OOP概念–static method

來源:互聯網
上載者:User

what is static method?

python2.73 doc

Static method objects 
Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved
from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation.
Static method objects are not themselves callable, although the objects they wrap usually are. Static method objects are created by the built-in staticmethod() constructor. 

不需要自己去調用

compare

用一般類方法和靜態方法和定義和調用作為比較
定義一個普通的class A

In [40]: class A(object):   ....:     def met(self,a,b):   ....:         print a,b   ....:

執行個體調用met方法

In [41]: a = A()In [42]: a.met(3,4)3 4

直接調用met方法

In [43]: A.met(3,4)---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-43-b2ef395d495e> in <module>()----> 1 A.met(3,4)TypeError: unbound method met() must be called with A instance as first argumen (got int instance instead)

出錯, 沒有Binder 方法

參數中加入我們上面建立的a執行個體

In [47]: A.met(a,3,4)3 4

只有使用類執行個體才可以調用

定義一個帶有靜態方法的類:

In [52]: class B():   ....:     @staticmethod   ....:     def met(a,b): #靜態方法第一個參數不需要是self    ....:         print a,b   ....:

執行個體後調用

In [55]: b = B()In [56]: b.met(3,4)3 4

直接調用

In [57]: B.met(3,4) #可以在不執行個體化的情況下直接調用函數3 4

靜態方法可以在不執行個體類的情況下直接調用,但是方法的第一個參數不能在寫成def(self,...)的形式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.