Python 類的屬性再解

來源:互聯網
上載者:User

標籤:靜態方法   nbsp   c++   預設   python 類   eating   world   全域   ini   

#類的屬性class A():        #定義一個類的屬性,類似於c++中的靜態變數        num=0        def __init__(self):                #執行個體對象屬性定義賦值                self.name = "hha"                def add(self):                #類屬性的調用                A.num += 1a = A()a.add()a.add()print(A.num)
#類中的方法class Dog():        #系統預設執行個體方法        def __init__(self):                self.name = "tom"        #自訂執行個體方法        def eat(self):                print("eating ...")        #類屬性        age = 12        #類方法的聲明        @classmethod        def setage(cls):                #這裡的cls變數表示類變數,可以直接操作類屬性,不要和self同名                cls.age += 2        #靜態方法--類似於c++中的全域函數        #和類方法的區別是沒有cls形參        @staticmethod        def show():                print("hell world .")‘‘‘類方法和靜態方法 既可以通過類名調用,也可以通過執行個體對象調用類方法主要為了操作類屬性靜態方法與類沒啥關係,類似於將main函數封裝到類中的感覺‘‘‘d = Dog()d.eat()d.setage()print("-----1------")print(Dog.age)print(d.age)Dog.setage()print("-----2------")print(Dog.age)print("----3-----")d.show()print("----4--------")Dog.show()

 

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.