Python——獻給那些對Python面
- 2020 年 1 月 8 日
- 筆記
面向對象,看似不難。有的同學學過之後,還是不知道如何去使用它。有時候編寫程式碼,寫著寫著就遇到坑了,比如寫著寫著就連你自己也在懷疑到底是不是面向對象編程了。
因此,本人想了一個比較簡單的例子,來用面向對象的方式去思考它,去編碼。那麼,我不會做過多的說明,我想我的程式碼應該是最容易讓人看懂的!
#coding:utf-8 class OS: #描述作業系統對象 def __init__(self, os_name): self.os_name = os_name def start_install(self): print("start install os:{0}".format(self.os_name)) class Host: #描述主機對象 def __init__(self, host_id, brand, cpu, ram, disk): self.host_id = host_id self.brand = brand self.cpu = cpu self.ram = ram self.disk = disk self.os_type = None def power_off(self): print("host id:{0} Shutdown..".format(self.host_id)) def power_on(self): print("host id:{0} Boot..".format(self.host_id)) def install_os(self, os_name): #伺服器(host)可以安裝作業系統 os = OS(os_name) os.start_install() self.os_type = os.os_name class DataCenter: #描述數據中心對象 def __init__(self): self.hosts_list = [] def add_host(self, host_id, brand, cpu, ram, disk): #數據中心裡可以添加伺服器(host) host = Host(host_id, brand, cpu, ram, disk) self.hosts_list.append(host) def search_host(self, host_id): for host in self.hosts_list: if host.host_id == host_id: return host return False if __name__ == '__main__': dc = DataCenter() dc.add_host(201, "IBM", "16個", "128GB", "9TB") host = dc.hosts_list[0] print(host.host_id, host.brand, host.cpu, host.ram, host.disk ) print(host.os_type) host.install_os("ubuntu14.04") print(host.os_type) host.power_on() host.power_off() search_host_ret = dc.search_host(201) print(search_host_ret.disk)其實你可以這樣思考:
1、一個數據中心機房,可以有伺服器,那麼數據中心可以添加伺服器,因此,描述數據中心對象的類可以有一個添加伺服器的方法
2、那麼,一台伺服器可以有品牌,CPU,記憶體等等,那麼描述伺服器對象的類,應該有這些屬性,並且,伺服器還可以安裝作業系統,那麼應該也給他設計一個安裝作業系統的方法
3、既然,伺服器可以安裝作業系統,那麼在我的設計里,我把作業系統也看成了一個對象,描述作業系統對象的類中有作業系統名稱,以及一個具體的安裝方法
最後,對於那些還比較茫然的同學看了此文之後,會不會有點啟發呢?我這裡的例子只是起到一個拋磚引玉的作用,水平有限,還望廣大python愛好者批評並指出。非常感謝!