python物件導向——類屬性和執行個體屬性

來源:互聯網
上載者:User

標籤:python

#coding:utf-8#描述橘子物件的類class Orange:    def __init__(self, weight):        self.weight = weight #執行個體屬性    def get_weight(self):        print(self.weight)class HostInfo:    info = [] #類屬性    def add_host(self, hostname, ip):        self.info.append({"hostname":hostname, "ip":ip})    def get_info(self):        print(self.info)if __name__ == "__main__":    o1 = Orange(1.5) #橘子1 重量1.5    o2 = Orange(2.3) #橘子2 重量2.3    o1.get_weight() #擷取重量    o2.get_weight()#橘子1的重量是1.5,橘子2的重量是2.3,這個所謂的重量(資料)被稱為屬性,屬性通常是可變的,#橘子類的每一個執行個體都會有重量這個屬性,但是每個執行個體的屬性給定的資料會不相同,也可能相同    h1 = HostInfo() #對象h1增加資料    h1.add_host("pc","192.168.1.2")    h2 = HostInfo() #對象h2增加兩條資料    h2.add_host("pc","192.168.1.2")    h2.add_host("pc","192.168.1.2")    h1.get_info() #不管是誰添加,大家都能擷取到主機資訊,    h2.get_info()#結論:類屬性共用於所有執行個體,執行個體屬性只屬於執行個體本身


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.