Python 模块
组织 code 到模块使用导入, 从-导入, __name__, and 标准库.
你将学到
- 创建 and 导入你的 own 模块
- Use 导入 and 从-导入语法
- 理解如果 __name__ == '__main__' guard
- Explore 键标准库 模块
- Control 什么获取 exported 使用 __all__
概念讲解
What Is a Module?
module 是 simply a .py file. The filename becomes the module name. Modules let you organize code into reusable files instead of one giant script:
project/
├── main.py
├── utils.py ← this is a module named "utils"
└── models.py ← this is a module named "models"
Any Python file can be imported as a module. This is the foundation of code organization in Python — you split your program into logical files and import from them.
Importing
There are several import styles, each with different trade-offs:
# Import the whole module — must qualify with module name
import math
print(math.pi)
print(math.sqrt(16))
# Import specific names — no qualification needed
from math import pi, sqrt
print(pi)
print(sqrt(16))
# Import with an alias — useful for long names
import numpy as np
import datetime as dt
# Import everything (discouraged — pollutes namespace)
from math import *
Best practice: use import module or from module import specific_name. Avoid from module import * — it pollutes your namespace and makes it unclear where names came from, which can cause subtle bugs.
Creating Your Own Module
Save this as utils.py:
# utils.py
def greet(name):
return f"Hello, {name}!"
def double(x):
return x * 2
PI_APPROX = 3.14159
Then in 主要.py in the same directory:
# main.py
import utils
print(utils.greet("Ada")) # Hello, Ada!
from utils import greet, double
print(double(21)) # 42
Python looks for modules in the directories listed in sys.path — the current directory is usually first, which is why local modules are found automatically.
The __name__ Guard
Every module has a __name__ attribute. When you run a file directly, __name__ is "__main__". When it is imported, __name__ is the module name:
# mymodule.py
def main():
print("运行 program")
if __name__ == "__main__":
# This only runs when the file is executed directly
# NOT when it is imported
main()
This guard lets your file serve double duty: as a runnable script (python mymodule.py) and as an importable module (导入 mymodule). Without it, the code would run on import too, which is usually not what you want.
__all__ — Controlling Exports
Define __all__ in your module to specify what 从 模块 导入 * exports:
# utils.py
__all__ = ["greet", "双"] # only these are exported with *
def greet(name):
return f"Hello, {name}!"
def double(x):
return x * 2
def _internal():
pass # not exported — "私有" by convention
Names starting with _ are also excluded from 导入 * by convention. __all__ gives you explicit control over your module's public API.
Key Standard Library Modules
Python's "batteries 包含" standard library is one of its greatest strengths:
os— operating system interface (paths, env vars, processes)sys— interpreter-specific functions (argv, exit, path)math— mathematical functions and constantsdatetime— date and time manipulationJSON— JSON encoding and decodingre— regular expressions集合— specialized containers (Counter, defaultdict, namedtuple)itertools— efficient iteration utilitiespathlib— object-oriented path handlingrandom— random number generationlogging— flexible logging system
import os, sys, math, random
from collections import Counter
print(os.getcwd()) # current working directory
print(sys.version) # Python version
print(math.factorial(5)) # 120
print(random.randint(1, 100)) # random int 1-100
print(Counter("aabbbcccc")) # Counter({'c': 4, 'b': 3, 'a': 2})
You rarely need to install external packages for common tasks — check the standard library first.
示例代码
# --- Imagine this is saved as utils.py ---
# def greet(name):
# return f"Hello, {name}!"
# def double(x):
# return x * 2
# PI_APPROX = 3.14159
# --- This is main.py ---
# Importing the standard library
import math
import random
import sys
from collections import Counter, defaultdict
from datetime import datetime
# math module
print(f"Pi: {math.pi:.4f}")
print(f"Factorial 5: {math.factorial(5)}")
print(f"GCD of 12 and 18: {math.gcd(12, 18)}")
# random module
print(f"Random int 1-100: {random.randint(1, 100)}")
print(f"Choice: {random.choice(['apple', 'banana', 'cherry'])}")
# collections module
word_count = Counter("the quick brown fox jumps over the lazy dog the")
print(f"Top 3 words: {word_count.most_common(3)}")
# defaultdict — no KeyError for missing keys
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dict(dd))
# sys module
print(f"Python version: {sys.version_info.major}.{sys.version_info.minor}")
# datetime module
now = datetime.now()
print(f"Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# The __name__ guard pattern
if __name__ == "__main__":
print("This runs only when executed directly, not on import")
Demonstrates importing and using 标准库 模块: math (pi, factorial, gcd), random (randint, choice), 集合 (计数器, defaultdict), sys (version), and datetime. __name__ guard at 底部 shows 标准模式.
动手试一试
- JSON Formatter
JSON 模块是 one 的大多数 used 标准库 模块.
- Regex Tester
re 模块 provides regex — 测试模式 used in Python code.
常见错误
错误写法
Using '从模块导入 *' 哪个 pollutes 命名空间
正确做法
Wildcard 导入制作它 unclear 哪里 names come 从 and 能 cause name collisions. Use '导入模块' or '从模块导入 specific_name'. 如果你 必须 use *, 定义 __all__ in 模块到 control 导出.
错误写法
Forgetting 如果 __name__ == '__main__' guard in scripts 那个是 也模块
正确做法
不使用 guard, code 运行 on 导入也. 总是 wrap script-execution code in '如果 __name__ == "__main__":' 所以 file 能是 两者都运行 directly and imported as 模块不使用边 副作用.
相关资源
相关速查表
- Python Cheatsheet
导入语法, 标准库 overview, and __name__ guard.
练习 Python 模块
5 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。