Python Learning-面向?qū)ο缶幊?類 二

目前為止,繼承可能讓人費(fèi)解,子類和父類擁有一樣的屬性和方法(行為),那這個(gè)子類還有什么意義?

實(shí)際上,通過(guò)繼承,可以大大的節(jié)省重新寫代碼的工作,并且,子類是可以擁有個(gè)性化的屬性與方法的

定義子類的專屬屬性和方法

class Store():
    """模擬一個(gè)小商店"""
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化屬性store_name和store_type"""
        self.store_name = store_name
        self.store_type = store_type
        self.commodity_list = commodity_list
        
    def open_store(self):
        """開始營(yíng)業(yè)"""
        print(self.store_name, '開始營(yíng)業(yè)')
        
    def close_sotre(self):
        """商店打烊"""
        print(self.store_name, '已經(jīng)打烊')
        
    def sell(self, commodity, quantity):
        """進(jìn)貨"""
        if commodity not in self.commodity_list.keys():
            print('本商店沒有'+commodity)
            return

        self.commodity_list[commodity] += quantity
        print('商品'+commodity+'進(jìn)貨了'+str(quantity)+'件')
    
    def stock(self, commodity, quantity):
        """售貨"""
        if commodity not in self.commodity_list.keys():
            self.commodity_list[commodity] = quantity
            print('新增商品'+commodity+str(quantity)+'件')
            return
        
        if self.commodity_list[commodity] >= quantity:
            self.commodity_list[commodity] += quantity
            print('商品'+commodity+'出售了'+str(quantity)+'件')
        else:
            print('商品'+commodity+'數(shù)量不足,無(wú)法出售,請(qǐng)忙進(jìn)貨')
            

class FoodStore(Store):
    """食品小店"""
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化"""
        # 調(diào)用父類中的構(gòu)造方法,通過(guò)下面的代碼讓子類包含父類中的屬性與方法
        super().__init__(store_name, store_type, commodity_list)
        
        # 小紅的食品小店安裝了一個(gè)自動(dòng)問候器,每當(dāng)有顧客上門的時(shí)候就會(huì)發(fā)發(fā)問候
        self.greetings = 'Welcome. Nice to meet you!'
    
    def say_hello(self):
        """向顧客發(fā)出問候語(yǔ)"""
        print(self.greetings)
    
# 定義一個(gè)商品清單
food_list = {'apple':100, 'milk':210, 'pear':72}
# 實(shí)例化一個(gè)叫商店叫美麗商店
food_store = FoodStore('美麗商店', 'supermarket', food_list)

# 訪問父類中的方法與屬性
print(food_store.commodity_list)
# 出售5個(gè)蘋果
food_store.sell('apple',5)

print('-'*10)

# 訪問子類的方法與屬性
print(food_store.greetings)
# 訪問子類中的方法
food_store.say_hello()

輸出:

{'apple': 100, 'milk': 210, 'pear': 72}
商品apple進(jìn)貨了5件
----------
Welcome. Nice to meet you!
Welcome. Nice to meet you!

self.greetings = 'Welcome. Nice to meet you!'是為子類定義的一個(gè)屬性,這里沒有通過(guò)傳遞的方式來(lái)初始化參數(shù),而是給了一個(gè)默認(rèn)值

def say_hello(self):該方法是子類中自定義的方法,用來(lái)打印問候語(yǔ)

變量與屬性

class Store():
    """模擬一個(gè)小商店"""
    # --略--
    
            
class FoodStore(Store):
    """食品小店"""
    
   def __init__(self, store_name, store_type, commodity_list):
        """初始化"""
        # 調(diào)用父類中的構(gòu)造方法,通過(guò)下面的代碼讓子類包含父類中的屬性與方法
        super().__init__(store_name, store_type, commodity_list)
        
        # 小紅的食品小店安裝了一個(gè)自動(dòng)問候器,每當(dāng)有顧客上門的時(shí)候就會(huì)發(fā)發(fā)問候
        self.greetings = 'Welcome. Nice to meet you!'
    
    def say_hello(self):
        """向顧客發(fā)出問候語(yǔ)"""
        print(self.greetings)
        
# 定義一個(gè)商品清單
food_list = {'apple':100, 'milk':210, 'pear':72}
# 實(shí)例化一個(gè)叫商店叫美麗商店
food_store = FoodStore('美麗商店', 'supermarket', food_list)
# 訪問子類的方法與屬性
print(food_store.greetings)
# 訪問子類中的方法
food_store.say_hello()

# 訪問類中的變量
print(FoodStore.greetings)
# 修改類中的變量值
FoodStore.greetings = 'hello'
print(FoodStore.greetings)

輸出:

Welcome. Nice to meet you!
Welcome. Nice to meet you!
Welcome. Nice to meet you!
hello

可以看出,如果要訪問類中的變量,需要通過(guò)類名+.訪問,而不是類的實(shí)例

而且可以在類的外部對(duì)變量值進(jìn)行訪問,同樣,屬性的值也可以在外部進(jìn)行訪問修改

如果子類定義一個(gè)方法與父類的方法名稱一樣,但是功能不一樣,結(jié)果會(huì)怎么樣呢?

重寫父類方法

如果在子類中定義了與父類中一樣的方法名,那Python會(huì)忽略父類中的該方法,轉(zhuǎn)而采用子類的方法;也就是說(shuō),子類可以在該方法中重新定義方法的行為

例:

class Store():
    """模擬一個(gè)小商店"""
    # --略--

class FoodStore(Store):
    """食品小店"""
    # 問候語(yǔ)
    greetings = 'Welcome. Nice to meet you!'
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化"""
        # 調(diào)用父類中的構(gòu)造方法,通過(guò)下面的代碼讓子類包含父類中的屬性與方法
        super().__init__(store_name, store_type, commodity_list)
    
    def say_hello(self):
        """向顧客發(fā)出問候語(yǔ)"""
        print(FoodStore.greetings)

    def open_store(self, week_day):
        """開始營(yíng)業(yè)"""

        # 如果是星期日,則不休息一天
        if week_day == 7:
            print("今天不營(yíng)業(yè)!")
        else:
            print(self.store_name, '開始營(yíng)業(yè)')
        
        
# 定義一個(gè)商品清單
food_list = {'apple':100, 'milk':210, 'pear':72}
# 實(shí)例化一個(gè)叫商店叫美麗商店
food_store = FoodStore('美麗商店', 'supermarket', food_list)
# 調(diào)用方法
food_store.open_store(7)

輸出:

今天不營(yíng)業(yè)!

def open_store(self, week_day):重寫了父類的open_store()方法;這里,該方法接收一個(gè)表示星期幾的參數(shù),如果是星期日(7)則本天休息一天不營(yíng)業(yè)

通過(guò)輸出可以看出,在調(diào)用opne_store()方法的時(shí)候,Python調(diào)用的是子類中的方法

將類封裝進(jìn)模塊中,使用的時(shí)候?qū)腩?/h3>

將下面代碼保存到store.py文件中

class Store():
    """模擬一個(gè)小商店"""
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化屬性store_name和store_type"""
        self.store_name = store_name
        self.store_type = store_type
        self.commodity_list = commodity_list
        
    def open_store(self):
        """開始營(yíng)業(yè)"""
        print(self.store_name, '開始營(yíng)業(yè)')
        
    def close_sotre(self):
        """商店打烊"""
        print(self.store_name, '已經(jīng)打烊')
        
    def sell(self, commodity, quantity):
        """進(jìn)貨"""
        if commodity not in self.commodity_list.keys():
            print('本商店沒有'+commodity)
            return

        self.commodity_list[commodity] += quantity
        print('商品'+commodity+'進(jìn)貨了'+str(quantity)+'件')
    
    def stock(self, commodity, quantity):
        """售貨"""
        if commodity not in self.commodity_list.keys():
            self.commodity_list[commodity] = quantity
            print('新增商品'+commodity+str(quantity)+'件')
            return
        
        if self.commodity_list[commodity] >= quantity:
            self.commodity_list[commodity] += quantity
            print('商品'+commodity+'出售了'+str(quantity)+'件')
        else:
            print('商品'+commodity+'數(shù)量不足,無(wú)法出售,請(qǐng)忙進(jìn)貨')

然后將下面代碼保存到my_store.py文件中,然后導(dǎo)入sotre模塊中的Store類

# 導(dǎo)入sotre模塊中的Store類
form store import Store

class FoodStore(Store):
    """食品小店"""
    # 問候語(yǔ)
    greetings = 'Welcome. Nice to meet you!'
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化"""
        # 調(diào)用父類中的構(gòu)造方法,通過(guò)下面的代碼讓子類包含父類中的屬性與方法
        super().__init__(store_name, store_type, commodity_list)
    
    def say_hello(self):
        """向顧客發(fā)出問候語(yǔ)"""
        print(FoodStore.greetings)

    def open_store(self, week_day):
        """開始營(yíng)業(yè)"""

        # 如果是星期日,則不休息一天
        if week_day == 7:
            print("今天不營(yíng)業(yè)!")
        else:
            print(self.store_name, '開始營(yíng)業(yè)')

也可以將Store類與FoodStore類都保存到一個(gè)類中,然后在主程序中調(diào)用

將Store類與FoodStore類都保存到store.py文件中,然后在main.py文件中引用它們

sotre.py文件如下:

class Store():
    """模擬一個(gè)小商店"""
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化屬性store_name和store_type"""
        self.store_name = store_name
        self.store_type = store_type
        self.commodity_list = commodity_list
        
    def open_store(self):
        """開始營(yíng)業(yè)"""
        print(self.store_name, '開始營(yíng)業(yè)')
        
    def close_sotre(self):
        """商店打烊"""
        print(self.store_name, '已經(jīng)打烊')
        
    def sell(self, commodity, quantity):
        """進(jìn)貨"""
        if commodity not in self.commodity_list.keys():
            print('本商店沒有'+commodity)
            return

        self.commodity_list[commodity] += quantity
        print('商品'+commodity+'進(jìn)貨了'+str(quantity)+'件')
    
    def stock(self, commodity, quantity):
        """售貨"""
        if commodity not in self.commodity_list.keys():
            self.commodity_list[commodity] = quantity
            print('新增商品'+commodity+str(quantity)+'件')
            return
        
        if self.commodity_list[commodity] >= quantity:
            self.commodity_list[commodity] += quantity
            print('商品'+commodity+'出售了'+str(quantity)+'件')
        else:
            print('商品'+commodity+'數(shù)量不足,無(wú)法出售,請(qǐng)忙進(jìn)貨')
            
            
class FoodStore(Store):
    """食品小店"""
    # 問候語(yǔ)
    greetings = 'Welcome. Nice to meet you!'
    
    def __init__(self, store_name, store_type, commodity_list):
        """初始化"""
        # 調(diào)用父類中的構(gòu)造方法,通過(guò)下面的代碼讓子類包含父類中的屬性與方法
        super().__init__(store_name, store_type, commodity_list)
    
    def say_hello(self):
        """向顧客發(fā)出問候語(yǔ)"""
        print(FoodStore.greetings)

    def open_store(self, week_day):
        """開始營(yíng)業(yè)"""

        # 如果是星期日,則不休息一天
        if week_day == 7:
            print("今天不營(yíng)業(yè)!")
        else:
            print(self.store_name, '開始營(yíng)業(yè)')

main.py文件如下:

# 導(dǎo)入一個(gè)模塊下的兩個(gè)類
from store import Store,FoodStore

# 定義一個(gè)商品清單
food_list = {'apple':100, 'milk':210, 'pear':72}
# 實(shí)例化一個(gè)Store對(duì)象
my_store = Store('我的商店', 'supermarket', food_list)
# 開始營(yíng)業(yè)
my_store.open_store()

# 實(shí)例化一個(gè)叫商店叫美麗商店
food_store = FoodStore('美麗商店', 'supermarket', food_list)
# 開始營(yíng)業(yè)
food_store.open_store(7)

也可以只導(dǎo)入模塊名,通過(guò).符號(hào)來(lái)訪問類

# 導(dǎo)入一個(gè)模塊下的兩個(gè)類
improt store as s

# 定義一個(gè)商品清單
food_list = {'apple':100, 'milk':210, 'pear':72}
# 實(shí)例化一個(gè)Store對(duì)象
my_sotre = s.Store('我的商店', 'supermarket', food_list)
# 開始營(yíng)業(yè)
my_store.open_store()

# 實(shí)例化一個(gè)叫商店叫美麗商店
food_store = s.FoodStore('美麗商店', 'supermarket', food_list)
# 開始營(yíng)業(yè)
food_store.open_store(7)

輸出:

我的商店 開始營(yíng)業(yè)
今天不營(yíng)業(yè)!

Python標(biāo)準(zhǔn)庫(kù)

安裝好的Python包含一組標(biāo)準(zhǔn)庫(kù),在導(dǎo)入標(biāo)準(zhǔn)庫(kù)中的模塊與函數(shù)時(shí),與上面的原理是一樣的

并且,多人協(xié)作的時(shí)候,也只可以通過(guò)上面的方式導(dǎo)入別人寫好的模塊

目錄
上一章 Python Learning-面向?qū)ο缶幊?類 一
下一章 Python Learning-文件處理

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容