Python實(shí)例方法 靜態(tài)方法 類方法

@staticmethod和@classmethod的區(qū)別

  • class 類
  • @staticmethod
  • @classmethod

首先創(chuàng)建一個(gè)類,如果想要調(diào)用Student類中的方法get_score(),就需要先創(chuàng)建類的實(shí)例,然后再用類的對象再去調(diào)用方法

In [3]: class Student():
   ...:     def __init__(self, name, score):
   ...:         self.name = name
   ...:         self.score = score
   ...:     def get_score(self):
   ...:         print('%s get %s ' % (self.name, self.score))
   ...:
   ...:

In [4]: student = Student('treehl', 100)

In [5]: student.get_score()
treehl get 100


@staticmethod和@classmethod一個(gè)是靜態(tài)方法,另一個(gè)是類的方法,兩個(gè)裝飾器的作用都可以使類不必再創(chuàng)建實(shí)例,直接用類來調(diào)用方法(類名.方法())

它們使用上的區(qū)別

  • @staticmethod不需要傳遞self,也不需要cls參數(shù),就跟使用函數(shù)一樣(類名.方法()或類名.屬性名)
  • @classmethod也不需要像實(shí)例方法一樣要傳遞self,但它需要cls參數(shù)(cls.類名()或cls.方法()或cls.屬性())

要理解這些,首先需要理解類屬性和實(shí)例屬性的區(qū)別


In [6]: class A():
   ...:     bar = 1
   ...:     def foo(self):
   ...:         print 'foo'
   ...:     @staticmethod
   ...:     def static_foo():
   ...:         print 'static_foo'
   ...:         print A.bar
   ...:     @classmethod
   ...:     def class_foo(cls):
   ...:         print 'class_foo'
   ...:         print cls.bar
   ...:         cls().foo()
   ...:

In [7]: A.static_foo()
static_foo
1

In [8]: A.class_foo()
class_foo
1
foo

歡迎訪問Treehl的博客
Github

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.列表解析式和字典解析式 列表解析式語法 [expr for value in collection if...
    MononokeHime閱讀 2,047評論 0 8
  • 1.1面向?qū)ο?面向?qū)ο?object-oriented ;簡稱: OO)至今還沒有統(tǒng)一的概念 我這里把它定義為:...
    TENG書閱讀 644評論 0 0
  • 實(shí)例方法: 顧名思義就是給實(shí)例使用的方法。就是我們使用最普遍的在類內(nèi)部定義的方法。 實(shí)例方法第一個(gè)參數(shù)為 self...
    4ffde5305e8f閱讀 1,320評論 0 8
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,101評論 0 9
  • 大學(xué)(university),“他”究竟是個(gè)什么東西,究竟是個(gè)怎樣的詞呢?是像字典里解釋的:泛指實(shí)施高等教育的學(xué)校...
    小安格閱讀 686評論 16 8

友情鏈接更多精彩內(nèi)容