1. 程式人生 > >《Python程式設計從入門到實踐》記錄之類儲存在模組及其匯入

《Python程式設計從入門到實踐》記錄之類儲存在模組及其匯入

目錄

1、模組中儲存多個類和匯入多個類

2、匯入整個莫模組

3、匯入模組中的所有類


為了使得程式儘可能整潔易讀,可以將類儲存在模組中,然後在主程式中匯入所需的模組。


1、模組中儲存多個類和匯入多個類

一般情況下,一個模組中的類之間應存在某種相關性,這裡為了說明此情況,將多個類儲存在一個模組中,實際應用中,最好還是將相關聯的儲存在一個模組中,不同模組中的類相對獨立,這樣有助於編寫程式和管理程式。

下邊例子還是汽車的例子,一個模組car.py中有兩個類Car和ElectricCar,並建立一個my_cars.py的檔案匯入這兩個類:

模組(car.py):

# car.py模組

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""一組用於表示燃油汽車和電動汽車的類"""


# 父類
class Car():
    """一次模擬汽車的簡單嘗試"""

    def __init__(self, make, model, year):
        """初始化描述汽車的屬性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0  # 指定預設值

    def get_descriptive_name(self):
        """返回整潔的描述性資訊"""
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        """列印一條指出汽車裡程的訊息"""
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        """將歷程表讀數設定為指定的值"""
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer")

    def increment_odometer(self, miles):
        """將里程錶讀數增加指定的量"""
        self.odometer_reading += miles


class Battery():
    """一次模擬電動汽車電瓶的簡單嘗試"""

    def __init__(self, battery_size=70):
        """初始化電瓶的屬性"""
        self.battery_size = battery_size

    def describe_battery(self):
        """列印一條描述電瓶容量的資訊"""
        print("This car has a " + str(self.battery_size) + "-kwh battery.")


# 子類,括號裡必須包含父類名稱
class ElectricCar(Car):
    """電動汽車的獨特之處"""

    # 接受建立Car例項所需的資訊
    def __init__(self, make, model, year):
        """初始化父類的屬性"""
        # super()特殊的函式,關聯父類和子類
        super().__init__(make, model, year)  # 初始化父類的屬性
        # Battery的一個例項作為ElectricCar的一個屬性
        self.battery = Battery(100)  # 初始化電動汽車的特有屬性

主程式(my_cars.py):

#!/usr/bin/env python
# -*- coding:utf-8 -*-


# 從car模組中匯入Car和ElectricCar類
from car import Car, ElectricCar

# 一個燃油汽車的例項
my_car = Car('audi', 'a6l', '2018')
print(my_car.get_descriptive_name())

# 一個電動汽車的例項
my_electric_car = ElectricCar('tesla', 'model s', '2017')
print(my_electric_car.get_descriptive_name())

執行結果:


2、匯入整個莫模組

上述例子是匯入具體的類,我們也可以匯入整個模組,使用句點表示法訪問需要的類。

下邊例子是匯入上述car整個模組,使用句點表示法訪問Car和ElectricCar類:

#!/usr/bin/env python
# -*- coding:utf-8 -*-


# 從car模組整個模組
import car

# 一個燃油汽車的例項
my_car = car.Car('audi', 'a6l', '2019')   # 句點法表示訪問需要的類
print(my_car.get_descriptive_name())

# 一個電動汽車的例項
my_electric_car = car.ElectricCar('tesla', 'model s', '2016')   # 句點法表示訪問需要的類
print(my_electric_car.get_descriptive_name())

執行結果:


3、匯入模組中的所有類

匯入模組中的所有類,類似於匯入模組中的所有函式一樣,使用的語法如下:

from module_name import*

這種方法簡單,但不推薦使用這種方法,推薦使用上述1、2方法

雖然不提倡,還是說明怎麼用瞭解一下,下邊例子就是匯入模組中的所有類:

#!/usr/bin/env python
# -*- coding:utf-8 -*-


# 從car模組匯入所有類
from car import*

# 一個燃油汽車的例項
my_car = Car('audi', 'a6l', '2019')   # 可以直接使用類
print(my_car.get_descriptive_name())

# 一個電動汽車的例項
my_electric_car = ElectricCar('tesla', 'model s', '2016')   # 可以直接使用類
print(my_electric_car.get_descriptive_name())

執行結果:


4、在一個模組中匯入另一個模組

將上述car模組分解為兩個模組:Car類模組(car.py)、ElectricCar和Battery組成的模組(electric_car.py)。

car.py模組:

"""一個可用於表示汽車的類"""
class Car():
    ---snip---

electric_car.py模組:

"""一組可用於表示電動汽車的類"""

# 匯入car模組中的Car類,從一個模組匯入另一個模組
from car import Car

class Battery():
    ---snip---

class ElectricCar(Car):
    ---snip---

主程式(my_cars.py):

from car import Car
from electric_car import ElectricCar

# 一個燃油汽車的例項
my_car = Car('audi', 'a6l', '2019')   # 可以直接使用類
print(my_car.get_descriptive_name())

# 一個電動汽車的例項
my_electric_car = ElectricCar('tesla', 'model s', '2016')   # 可以直接使用類
print(my_electric_car.get_descriptive_name())

執行結果: