包
我们已使用过单行代码、多行函数、独立程序以及同一目录下的多个模块。为了使Python
应用更具可扩展性,你可以把多个模块组织成文件层次,称之为包。
也许我们需要两种类型的天气预报:一种是次日的,一种是下周的。一种可行的方式是新
建目录sources,在该目录中新建两个模块daily.py 和weekly.py。每一个模块都有一个函数
forecast。每天的版本返回一个字符串,每周的版本返回包含7 个字符串的列表。
下面是主程序和两个模块(函数enumerate() 拆分一个列表,并对列表中的每一项通过for
循环增加数字下标)。
主程序是boxes/weather.py:
from sources import daily, weekly
print("Daily forecast:", daily.forecast())
print("Weekly forecast:")
for number, outlook in enumerate(weekly.forecast(), 1):
print(number, outlook)
模块1 是boxes/sources/daily.py:
def forecast():
'fake daily forecast'
return 'like yesterday'
模块2 是boxes/sources/weekly.py:
def forecast():
"""Fake weekly forecast"""
return ['snow', 'more snow', 'sleet',
'freezing rain', 'rain', 'fog', 'hail']
还需要在sources 目录下添加一个文件:init.py。这个文件可以是空的,但是Python 需要
它,以便把该目录作为一个包。
运行主程序weather.py:
$ python weather.py
Daily forecast: like yesterday
Weekly forecast:
1 snow
2 more snow
3 sleet
4 freezing rain
5 rain
6 fog
7 hail