Python類的靜態屬性、類方法、靜態方法

來源:互聯網
上載者:User

標籤:color   pre   nbsp   sage   類方法   就是   print   object   method   

1、靜態屬性。@property。作用就是把類的函數屬性,封裝成類似資料屬性。

class Student(object):     school=‘szu‘    @property    def printmassage(self):        print(‘aaaa‘)s1=Student()s1.printmassage    #aaaa

2、類方法:是類對象所擁有的方法,需要用修飾器@classmethod來標識其為類方法,對於類方法,第一個參數必須是類對象,一般以cls作為第一個參數,能夠通過執行個體對象和類對象去訪問。

類方法一般有兩個作用:一是訪問類屬性。二是修改類屬性

class Student(object):    school=‘szu‘    @classmethod    def printmassage(cls):        print(cls.school)    s1=Student()Student.printmassage()  #szus1.printmassage()       #szu

 

 3、靜態方法:靜態方法實際上是獨立的,依靠在類中,但實際是只是調取關係。只是名義上歸類管理,實際上就是一個工具包,可以供類和執行個體調用。靜態方法裡不能直接調用類方法,要調用必須加上類名字去調用。

class Student(object):    school=‘szu‘    @staticmethod    def printmassage():        print(Student.school)    @staticmethod    def func(x,y):        print(x,y)s1=Student()Student.printmassage()  #szus1.printmassage()       #szuStudent.func(1,2)   #1 2s1.func(1,2)            #1,2   

 

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.