python學習筆記之物件導向中的靜態方法、類方法、屬性方法總結

來源:互聯網
上載者:User

標籤:不可   構造   icm   ini   錯誤   not   python學習   call   highlight   

  • 靜態方法
  • 類方法
  • 屬性方法

一、靜態方法

可以利用@staticmethod裝飾器把一個方法變成一個靜態方法。靜態方法不可以方法執行個體變數或者類變數,也就是說不可以使用self.屬性這樣子調用執行個體屬性了。其實靜態方法就和類本身沒什麼關係了,它和類

唯一的關聯就是需要通過類名來調用這個方法。

錯誤調用方式:

class Dog(object):    def __init__(self,name):        self.name = name    @staticmethod #把eat方法變為靜態方法    def eat(self):        print("%s is eating" % self.name)d = Dog("ChenRonghua")d.eat()

上面的調用會出以下錯誤,說是eat需要一個self參數,但調用時卻沒有傳遞,沒錯,當eat變成靜態方法後,再通過執行個體調用時就不會自動把執行個體本身當作一個參數傳給self了。

正確調用方法:

class Dog(object):    def __init__(self,name):        self.name = name    @staticmethod    def eat():        print(" is eating")d = Dog("ChenRonghua")d.eat()

或者:

lass Dog(object):    def __init__(self,name):        self.name = name    @staticmethod #把eat方法變為靜態方法    def eat(self):        print("%s is eating" % self.name)d = Dog("ChenRonghua")d.eat(d)

二、類方法

類方法是用@classmethod裝飾器來實現的,類方法只能訪問類變數,不能訪問執行個體變數。

class Dog(object):    def __init__(self,name):        self.name = name     @classmethod    def eat(self):        print("%s is eating" % self.name) d = Dog("ChenRonghua")d.eat()

上面的name是構造方法裡面定義的,是一個執行個體變數,類方法是不能訪問的。所以會報錯:dog沒有name屬性

對比下面的:

class Dog(object):    name = "我是類變數"    def __init__(self,name):        self.name = name     @classmethod    def eat(self):        print("%s is eating" % self.name)  d = Dog("ChenRonghua")d.eat()  #執行結果 我是類變數 is eating

三、屬性方法

屬性方法就是通過@property把一個方法變成靜態屬性

class Dog(object):     def __init__(self,name):        self.name = name     @property    def eat(self):        print(" %s is eating" %self.name)  d = Dog("ChenRonghua")d.eat()

  調用會出以下錯誤, 說NoneType is not callable, 因為eat此時已經變成一個靜態屬性了, 不是方法了, 想調用已經不需要加()號了,直接d.eat就可以了

正確的使用:

d = Dog("ChenRonghua")d.eat 輸出 ChenRonghua is eating

  

python學習筆記之物件導向中的靜態方法、類方法、屬性方法總結

相關文章

聯繫我們

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