Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第3章 模块化

对于大多数的软件系统,模块化是一个重要的属性,因为我们能够通过模块来创建独立、可重用的部件,我们可以把模块结合在一起,以新的方式来解决不同的问题。与大多数编程语言类似,Python中最细微的模块化功能就是定义可重用的函数,同时Python也为我们提供了其他强大的模块化机制。

相关函数的集合组合成一个整体的形式,该形式称为模块(module)。模块就是可以被其他代码引用的源代码文件,可以在一个模块中使用定义在另一个模块中的函数。只要注意避免任何循环依赖,那模块就是简单且灵活的组织程序的方式。

在前面的章节中,我们了解到可以将模块导入到REPL中。本章将向你展示如何以程序或脚本的方式直接执行模块。作为本章内容的一部分,我们将研究Python执行模型,以确保你能完全理解代码是何时求值且执行的。在本章最后,我们将向你展示如何使用命令行参数将基本配置数据导入到程序中并使程序可执行。

本章将从上一章结尾处开发的从网上获取文本文档的代码片段开始。我们通过将其组织成一个完全成熟的Python模块来阐述该代码。

本节从第2章中的代码片段开始。打开一个文本编辑器——最好是一个支持Python语法高亮显示的文本编辑器,并且在按Tab键时,该编辑器可以将代码格式配置为每个缩进级别插入4个空格。你还应该检查编辑器是否使用UTF-8编码保存文件,这是Python 3运行时期望的。

在用户目录下创建一个名为pyfund的目录,我们将把本章的代码放在该目录下。

所有Python源文件都使用.py扩展名,把在REPL编写的代码段放入名为pyfund/words.py的文件中。该文件的内容应如下所示:

from urllib.request import urlopen ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626