Python普通方法、靜態方法、類方法

來源:互聯網
上載者:User

標籤:的區別   def   proc   static   title   tty   self   sso   method   

開始
# -*-coding:utf-8-*-# 普通方法,類方法,靜態方法的區別__metaclass__ = typeclass Tst:    name = ‘tst‘    data = ‘this is data‘    # 普通方法    def normalMethod(self, name):        print self.data, name    # 類方法,可以訪問類屬性    @classmethod    def classMethod(cls, name):        print cls.data, name    # 靜態方法,不可以訪問類屬性    @staticmethod    def staticMethod(name):        print name
測試
  • 三種方法都可以通過執行個體來調用,但是靜態方法和類方法無法訪問執行個體屬性,所以更改了tst.data僅對普通方法起了作用
tst = Tst()tst.data = ‘this is new‘tst.normalMethod(‘name‘)tst.staticMethod(‘name‘)tst.classMethod(‘name‘)#結果this is new namenamethis is data name
區別
  • 普通方法不能通過類名調用,但是靜態方法和類方法是可以的
# error普通方法必須通過執行個體調用# Tst.normalMethod(‘name‘)Tst.classMethod(‘name‘)Tst.staticMethod(‘name‘)#結果this is data namename
總結
  • 普通方法,可以通過self訪問執行個體屬性
def normalMethod(self,data)
  • 類方法,可以通過cls訪問類屬性
@classmethoddef classMethod(cls,data)
  • 靜態方法,不可以訪問,通過傳值的方式
@staticmethoddef staticMethod(data)

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.