1. 程式人生 > >Python——獻給那些對Python面向對象編程不知如何應用的同學們

Python——獻給那些對Python面向對象編程不知如何應用的同學們

也看 boot class 自己 utf earch 安裝 過多 是不是

面向對象,看似不難。有的同學學過之後,還是不知道如何去使用它。有時候編寫代碼,寫著寫著就遇到坑了,比如寫著寫著就連你自己也在懷疑到底是不是面向對象編程了。

因此,本人想了一個比較簡單的例子,來用面向對象的方式去思考它,去編碼。那麽,我不會做過多的說明,我想我的代碼應該是最容易讓人看懂的!

#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愛好者批評並指出。非常感謝!


Python——獻給那些對Python面向對象編程不知如何應用的同學們