NOTE基于 Python 3。
import
import mathprint(math.sqrt(2))
from math import sqrt, piprint(sqrt(2), pi)
import datetime as dt模块是一个 .py 文件。import math 之后通过 math.sqrt 访问。from math import sqrt 将 sqrt 导入当前命名空间。as 用于指定别名。
同一个模块只执行顶层代码一次,结果缓存在 sys.modules 里。
from module import * 会导入模块中的全部名字,不建议使用。
命令行参数在 sys.argv:
import sysprint(sys.argv) # [脚本路径, 后续参数...]包与 init.py
含 __init__.py 的目录是包,可以 import pkg.mod(Packages)。__init__.py 可以为空。包内可用相对导入:from . import echo。
没有 __init__.py 的目录也可能作为 namespace package(PEP 420)。
sound/ __init__.py effects/ __init__.py echo.pyfrom sound.effects import echo 后使用 echo.surround()。包内子模块也是完整模块名:sound.effects.echo。
打包发布见 pyproject.toml。
if name == ‘main’
脚本直接运行时,__name__ 为 '__main__';被 import 时为模块名(如 'mymodule')。常见写法:
def main(): ...
if __name__ == "__main__": main()import mymodule 不执行 main();python mymodule.py 会执行。也可用 python -m pkg.module(-m 搜索)。
print 与 input
print 可以把对象写到文件:print(x, file=f)。input(prompt='') 从标准输入读一行,返回 str(去掉末尾换行),数值运算再 int() / float()。
pprint 用于格式化输出嵌套结构。json.dumps 用于输出 JSON。字符串格式化见 f-string / str.format。
open 读写与 with
open(file, mode='r', encoding=None, ... ) 返回 text 或 binary 流。文本模式默认编码依平台,通常显式传 encoding='utf-8'(UTF-8 模式 在 3.7+ 可通过 -X utf8 或 PYTHONUTF8 影响默认行为)。
常用模式:'r' 读、'w' 写(清空)、'a' 追加、'x' 独占创建、'r+' 读写;加 'b' 为二进制(encoding 无效)。
with open("notes.txt", "w", encoding="utf-8") as f: f.write("第一行\n") f.writelines(["第二行\n", "第三行\n"])
with open("notes.txt", "r", encoding="utf-8") as f: whole = f.read() # 整个文件 str # 或 for line in f: # 逐行,省内存 # 或 lines = f.readlines()文件对象实现上下文管理器,离开 with 时会调用 close()。不使用 with 时需要调用 f.close()。
二进制:with open("img.bin", "rb") as f: data = f.read()。CSV、JSON 见 csv、json。
文本流常用方法见 io.IOBase:
| 方法 | 作用 |
|---|---|
read / readline / readlines | 读 |
write / writelines | 写 |
seek(offset, whence=0) | 移动文件指针;whence 0 开头、1 当前、2 末尾 |
tell() | 当前指针位置 |
flush() | 刷缓冲区 |
close() | 关闭(with 会自动调) |
'w+' 写完后若要读回去,须先 seek(0)。
路径:pathlib 与 os.path
pathlib(3.4+)用面向对象路径替代字符串拼接。常用 Path:
from pathlib import Path
p = Path("data") / "logs" / "app.log" # 跨平台拼接p.parent.mkdir(parents=True, exist_ok=True)p.write_text("hello\n", encoding="utf-8")text = p.read_text(encoding="utf-8")print(p.suffix, p.stem, p.resolve())常用:exists()、is_file()、is_dir()、glob()、iterdir()、rename()、unlink()(删文件)。PurePath 不做 I/O,只算路径。
os.path 提供基于字符串的路径操作:os.path.join、dirname、basename、abspath、splitext。可与 pathlib 互转:Path(p)、str(path)。获取文件状态可使用 Path.stat() 或 os.stat。
当前工作目录:Path.cwd();改变用 os.chdir(改变进程全局 cwd)。
os 常用
os 提供操作系统接口;与路径无关的常见调用:
os.environ:环境变量映射,可读可写;取值也可用os.getenv。os.listdir(path)/os.scandir(path):列目录(后者更高效,可拿类型信息)。os.mkdir/os.makedirs:建目录;makedirs(..., exist_ok=True)类似Path.mkdir。os.walk(top):递归遍历目录树(os.walk)。os.replace:覆盖式重命名,跨平台比rename稳。os.getpid()、os.cpu_count():进程 id、CPU 数。
pathlib 与 os.environ 常一起使用。子进程见 subprocess。
class
Classes:使用 class 定义类。实例属性写在 self 上。方法的第一个参数约定为 self,调用时自动传入。
class Dog: kind = "canine" # 类属性,共享
def __init__(self, name): self.name = name # 实例属性
def bark(self): return f"{self.name}: woof!"
d = Dog("Rex")print(d.bark(), Dog.kind)__init__ 在实例创建后初始化,不是分配内存的构造器(那是 __new__)。__repr__ / __str__ 控制 repr(obj) 与 str(obj) / print(obj)。
继承:
class Animal: def __init__(self, name): self.name = name
class Cat(Animal): def __init__(self, name, indoor=True): super().__init__(name) # 调父类 __init__ self.indoor = indoorsuper() 在单继承里找父类实现;多继承按 MRO(方法解析顺序)线性化。
数据 vs 方法:Python 不强制访问控制。约定 _name 表示内部使用;__name 触发名称改写(name mangling),改写后仍可通过 _类名__属性 访问。@property 把方法当属性读;@classmethod / @staticmethod 见 Class and Instance Variables。
类本身也是对象,可传参、可放入容器,见 Odds and Ends。
类型注解
PEP 484 函数注解、PEP 526 变量注解、PEP 585 内置泛型 list[int]、PEP 604 的 X | Y(3.10+)。运行时默认不强制检查;静态检查可用 mypy。
def greet(name: str, times: int = 1) -> str: return (name + "! ") * times
def sum_all(nums: list[float]) -> float: return sum(nums)
from typing import Optional
def find(items: list[str], key: str) -> Optional[str]: return key if key in items else None常用 typing 名字:
Optional[T]— 等价于T | None(3.10+ 也可写Union或|)。Union[A, B]/A | B— 多种类型之一。list[int]、dict[str, int]— 泛型容器(3.9+ 内置泛型;旧代码见List、Dictfrom typing)。Callable[[int, str], bool]— 可调用签名。Iterable[T]、Sequence[T]— 只读迭代 / 序列抽象。TypedDict、Protocol、NamedTuple— 结构化数据。
变量也可注解:count: int = 0。类属性:class User: id: int; name: str。延迟解析字符串注解:from __future__ import annotations(3.7+;3.11+ 部分行为默认变化见 What’s New)。
typing.get_type_hints() 可在运行时取注解。
venv:虚拟环境
venv 创建轻量隔离环境,各自拥有 python 与 pip(或 ensurepip 引导),包安装不污染系统 Python。
python -m venv .venv# Windows PowerShell:.\.venv\Scripts\Activate.ps1# Unix / macOS:source .venv/bin/activate激活后 which python / where python 应指向 .venv。安装依赖:python -m pip install requests。冻结清单:python -m pip freeze > requirements.txt,再 python -m pip install -r requirements.txt。退出:deactivate。指定解释器版本:python3.12 -m venv .venv。
项目根常见 .venv/ 加入 .gitignore;依赖列表用 requirements.txt 或 pyproject.toml。
virtualenv 是第三方替代;conda 是另一套生态。教程:Virtual Environments and Packages。
标准库地图
Brief Tour of the Standard Library 与 stdlib index 是总入口。常用模块:
| 模块 | 一句话 |
|---|---|
| os | 操作系统接口:环境变量、进程 id、目录项、部分路径与权限原语。 |
| sys | 解释器相关:argv、path、stdin/stdout/stderr、版本与退出。 |
| json | JSON 与 Python 对象互转(dumps / loads / dump / load),非 Python 专有类型需默认处理。 |
| datetime | 日期与时间:date、time、datetime、timedelta,时区见 zoneinfo(3.9+)。 |
| pathlib | 面向对象的文件系统路径与常见 I/O 快捷方法。 |
| collections | 专用容器:Counter、deque、defaultdict、namedtuple 等。 |
| itertools | 迭代器代数:无穷序列、组合、链式、分组(惰性、省内存)。 |
| functools | 高阶函数:partial、reduce、lru_cache、wraps(装饰器元数据)。 |
| shutil | 高层文件操作:copyfile、move、rmtree。 |
| glob | glob.glob('*.py') 按通配符列文件。 |
| argparse | 命令行参数解析。 |
还常会用到:re、urllib / http、sqlite3、logging、unittest。
附录:import 形式速查
| 语句 | 效果 |
|---|---|
import mod | 绑定 mod 模块对象 |
import mod as m | 绑定别名 m |
from mod import a, b | 把 a、b 放入当前命名空间 |
from mod import a as x | 别名导入 |
from mod import * | 导入 __all__ 或公开名字(不推荐) |
from pkg.sub import obj | 导入子模块或子模块中的名字 |
from . import sibling | 包内相对导入 |
importlib.import_module('mod') | 动态导入(importlib) |
附录:open 模式与 pathlib 对照
| 需求 | open | pathlib(3.11+ 部分 API 更早) |
|---|---|---|
| 读文本 | open(p, encoding='utf-8').read() | Path(p).read_text(encoding='utf-8') |
| 写文本 | open(p, 'w', encoding='utf-8').write(s) | Path(p).write_text(s, encoding='utf-8') |
| 读字节 | open(p, 'rb').read() | Path(p).read_bytes() |
| 拼接路径 | os.path.join(a, b) | Path(a) / b |
| 是否存在 | os.path.exists(p) | Path(p).exists() |
| 列目录 | os.listdir(d) | Path(d).iterdir() |
附录:typing 常用符号(3.10+ 风格)
| 写法 | 含义 |
|---|---|
x: int | 变量为 int |
def f() -> None | 无返回值 |
list[str] | 字符串列表 |
dict[str, int] | 键 str、值 int |
tuple[int, ...] | 整数可变长元组 |
str | None / Optional[str] | 可为 None |
int | str | 联合类型 |
Callable[[int], str] | 接受 int 返回 str 的可调用 |
Literal["r", "w"] | 只能是列出的字面量 |
TypeVar('T') | 泛型类型变量 |
运行时默认不按注解校验对象。
参考
官方文档(中文版):
- Modules — import、模块搜索路径、包、
__init__.py、__name__ - Input and Output —
print、input、格式化、f-string、读写文件 intro - Classes — 属性、方法、继承、
super、私有约定 - Virtual Environments and Packages — venv 与 pip 工作流
- Brief Tour of the Standard Library — 标准库导览
- The import system — 导入语义、相对导入、namespace package
- pathlib —
Path/PurePath - os — 操作系统接口
- os.path — 路径字符串函数
- open() — 文件打开
- io — 流基类
- typing — 类型注解构造
- venv — 创建虚拟环境
- json — JSON
- datetime — 日期时间
- collections — 容器
- itertools — 迭代工具
- functools — 高阶函数工具
- sys — 解释器
- main — 主模块
PEP:
- PEP 484 — Type Hints
- PEP 526 — Syntax for Variable Annotations
- PEP 585 — Type Hinting Generics In Standard Collections
- PEP 604 — Allow writing union types as X | Y
- PEP 420 — Implicit Namespace Packages
- PEP 8 — Style Guide — import 顺序等
菜鸟教程:
- 菜鸟教程 · Python3 模块
- 菜鸟教程 · Python3 输入和输出
- 菜鸟教程 · Python3 文件方法
- 菜鸟教程 · OS 文件/目录
- 菜鸟教程 · Python3 面向对象
- 菜鸟教程 · 虚拟环境
- 菜鸟教程 · 类型注解
- 菜鸟教程 · 标准库概览