官术网_书友最值得收藏!

Introducing Python modules

For most beginner programmers, their first Python program is some version of the famous Hello World program. This program would look something like this:

print("Hello World!")

This one-line program would be saved in a file on disk, typically named something like hello.py, and it would be executed by typing the following command into a terminal or command-line window:

python hello.py

The Python interpreter would then dutifully print out the message you have asked it to:

Hello World!

This hello.py file is called a Python source file. When you are first starting out, putting all your program code into a single source file is a great way of organizing your program. You can define functions and classes, and put instructions at the bottom which start your program when you run it using the Python interpreter. Storing your program code inside a Python source file saves you from having to retype it each time you want to tell the Python interpreter what to do.

As your programs get more complicated, however, you'll find that it becomes harder and harder to keep track of all the various functions and classes that you define. You'll forget where you put a particular piece of code and find it increasingly difficult to remember how all the various pieces fit together.

Modular programming is a way of organizing programs as they become more complicated. You can create a Python module, a source file that contains Python source code to do something useful, and then import this module into your program so that you can use it. For example, your program might need to keep track of various statistics about events that take place while the program is running. At the end, you might want to know how many events of each type have occurred. To achieve this, you might create a Python source file named stats.py which contains the following Python code:

def init():
    global _stats
    _stats = {}

def event_occurred(event):
    global _stats
    try:
        _stats[event] = _stats[event] + 1
    except KeyError:
        _stats[event] = 1

def get_stats():
    global _stats
    return sorted(_stats.items())

The stats.py Python source file defines a module named stats—as you can see, the name of the module is simply the name of the source file without the .py suffix. Your main program can make use of this module by importing it and then calling the various functions that you have defined as they are needed. The following frivolous example shows how you might use the stats module to collect and display statistics about events:

import stats

stats.init()
stats.event_occurred("meal_eaten")
stats.event_occurred("snack_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("snack_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("diet_started")
stats.event_occurred("meal_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("diet_abandoned")
stats.event_occurred("snack_eaten")

for event,num_times in stats.get_stats():
    print("{} occurred {} times".format(event, num_times))

We're not interested in recording meals and snacks, of course—this is just an example—but the important thing to notice here is how the stats module gets imported, and then how the various functions you defined within the stats.py file get used. For example, consider the following line of code:

stats.event_occurred("snack_eaten")

Because the event_occurred() function is defined within the stats module, you need to include the name of the module whenever you refer to this function.

Note

There are ways in which you can import modules so you don't need to include the name of the module each time. We'll take a look at this in Chapter 3, Using Modules and Packages, when we look at namespaces and how the import command works in more detail.

As you can see, the import statement is used to load a module, and any time you see the module name followed by a period, you can tell that the program is referring to something (for example, a function or class) that is defined within that module.

主站蜘蛛池模板: 周口市| 宜章县| 西丰县| 图木舒克市| 浪卡子县| 蒙自县| 泸定县| 遵义市| 吉水县| 盘锦市| 家居| 神农架林区| 南丰县| 宜昌市| 北安市| 浪卡子县| 休宁县| 合水县| 鸡东县| 柞水县| 南乐县| 永安市| 屯昌县| 井陉县| 凭祥市| 青河县| 青田县| 姚安县| 朝阳区| 静安区| 福鼎市| 英德市| 华池县| 温州市| 襄城县| 西乌珠穆沁旗| 罗甸县| 本溪| 岢岚县| 手机| 滦南县|