python靜態屬性,靜態方法,類方法

來源:互聯網
上載者:User

標籤:return   一個   函數調用   通過   world   python   ram   TE   類的屬性   

#靜態屬性的作用是吧類的方法隱藏起來(可以把背後的邏輯隱藏起來),讓使用者感覺是在電泳屬性,而不是方法class Static:    attribute='屬性'    def __init__(self,parameter1,parameter2,parameter3):        self.parameter1 = parameter1        self.parameter2 = parameter2        self.parameter3 = parameter3    def test(self):        return ('test',self.parameter1)    @property    def print_static(self):        print(Static.attribute)        return ('這個是靜態屬性的結果 %s %s %s'%(self.parameter1,self.parameter2,self.parameter3))s=Static('hello','world','!')print(s.test())print(s.print_static)

靜態方法:

#靜態方法只是名義上歸類管理,不能使用類變數和執行個體變數,是類的工具包#我個人的理解是扯虎皮做大旗,靜態方法只是借用類的大樹下的一個獨立函數class Static:    attribute='屬性'    def __init__(self,parameter):        self.parameter=parameter    def test(self):        return ('test',self.parameter)    @staticmethod    def print_static(a,b,c):        print(Static.attribute)        return ('這個是靜態方法',a+b+c)s=Static('hello')print(s.test())print(Static.print_static(2,4,6))

類方法:

'''@classmethod 類方法是通過類裡面的函數調用類本身的屬性'''class Class():    attribute='類的屬性'#類的屬性    def __init__(self,parameter): #這裡的self是一個對象        self.parameter=parameter #執行個體的屬性    def test(self):        print(self)        return  ('類方法測試調用',self.parameter)    @classmethod#類方法只能調用類屬性,不能調用執行個體屬性    def print_class(cls): #這裡的cls是一個類        print(cls)        return ('通過類調用類的屬性',cls.attribute)x=Class('執行個體的屬性')print(x.test())print(x.parameter)print(Class.print_class())print(Class.attribute)


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.