Python
优雅、简洁、强大的通用编程语言 —— "人生苦短,我用 Python"
发展历史
诞生
1989 年圣诞节,荷兰程序员 Guido van Rossum 在阿姆斯特丹开始开发 Python,作为 ABC 语言的后继者。1991 年发布第一个公开版本(Python 0.9.0),已包含类、异常、函数、列表等核心特性。
版本演进
| 版本 | 时间 | 里程碑 |
|---|---|---|
| Python 0.9.0 | 1991 | 第一个公开发行版 |
| Python 1.0 | 1994 | 引入 lambda、map/filter/reduce |
| Python 2.0 | 2000 | 列表推导、垃圾回收、Unicode 支持 |
| Python 3.0 | 2008 | 不兼容 2.x,统一 Unicode、print 为函数、整数除法改 |
| Python 3.6 | 2016 | f-string、类型注解、async/await 稳定 |
| Python 3.8 | 2019 | 海象运算符 := |
| Python 3.10 | 2021 | 模式匹配(match)、联合类型 X | Y |
| Python 3.11 | 2022 | 大幅性能提升(CPython 提速 10-60%) |
| Python 3.12 | 2023 | 更灵活的 f-string、类型语法增强 |
| Python 3.13 | 2024 | 实验性 JIT 编译、去除 GIL 实验特性 |
Python 2 → 3 过渡
Python 2.7 发布于 2010 年,官方支持于 2020 年 1 月 1 日终止。建议所有新项目直接使用 Python 3.x。
设计哲学
Python 的核心理念在 PEP 20(The Zen of Python)中阐述:
优美优于丑陋(Beautiful is better than ugly)
明确优于隐式(Explicit is better than implicit)
简单优于复杂(Simple is better than complex)
复杂优于凌乱(Complex is better than complicated)
可读性很重要(Readability counts)
...安装与环境
下载
- 官网:https://www.python.org/downloads
- Windows:下载
.exe安装包,勾选 "Add Python to PATH" - macOS:下载
.pkg或使用 Homebrew:brew install python - Linux:包管理器安装
sudo apt install python3或编译源码
验证安装
bash
python --version # Python 3.13.x
python -c "print('Hello Python')"虚拟环境
虚拟环境是 Python 最佳实践,隔离不同项目的依赖:
bash
# 创建虚拟环境(Python 3.3+ 内置 venv)
python -m venv .venv
# 激活
# Windows (cmd): .venv\Scripts\activate
# Windows (PowerShell): .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
# 退出
deactivate包管理工具
| 工具 | 说明 | 状态 |
|---|---|---|
| pip | Python 官方包管理器 | 内置,标准工具 |
| pipenv | Pip + Virtualenv 整合 | 社区常用 |
| poetry | 现代依赖管理 + 构建 | 推荐新项目使用 |
| conda | 数据科学全家桶 | Anaconda 生态 |
| uv | Rust 写的超快速 pip/pipenv 替代 | 新兴工具 |
bash
# pip 常用命令
pip install requests # 安装包
pip install -r requirements.txt # 从文件安装
pip list # 列出已安装包
pip freeze > requirements.txt # 导出依赖
pip uninstall requests # 卸载
pip show requests # 查看包信息IDE / 编辑器
| 工具 | 特点 |
|---|---|
| PyCharm | JetBrains 出品,专业 Python IDE,社区版免费 |
| VSCode | 安装 Python 扩展后功能强大,轻量免费 |
| Jupyter Notebook | 交互式计算,数据科学标配 |
| IDLE | Python 自带简易 IDE,适合入门 |
基础语法
变量与类型
Python 是动态类型语言,变量无需声明类型:
python
# 基本类型
name = "Alice" # str
age = 30 # int
pi = 3.14159 # float
is_active = True # bool
nothing = None # NoneType
# 类型注解(Python 3.5+,可选,仅提示作用)
name: str = "Alice"
age: int = 30
# 多重赋值
a, b = 1, 2
a, b = b, a # 交换变量值,无需临时变量
# 海象运算符(Python 3.8+)
if (n := len(items)) > 10:
print(f"超过 {n} 个元素")基本数据类型
python
# 数字
type(42) # <class 'int'>
type(3.14) # <class 'float'>
type(1 + 2j) # <class 'complex'>
10 / 3 # 3.333...(真除法)
10 // 3 # 3(整除)
10 % 3 # 1(取余)
# 字符串
s1 = '单引号'
s2 = "双引号"
s3 = '''多行
字符串'''
s = f"Hello {name}" # f-string(Python 3.6+)
s = "Hello " + name # 拼接
s.upper(), s.lower(), s.strip()
s.split(','), ','.join(['a', 'b'])
s.replace('old', 'new')
s.startswith('He'), 'world' in s
# 布尔
True and False # False
True or False # True
not True # False
# 假值
# None, False, 0, 0.0, ''(空字符串), [](空列表), {}(空字典), ()(空元组)集合类型
python
# 列表(list)— 有序、可变
arr = [1, 2, 3, 4, 5]
arr.append(6) # 末尾添加
arr.insert(0, 0) # 指定位置插入
arr.pop() # 末尾删除
arr.remove(3) # 按值删除第一个
arr[0] # 索引
arr[-1] # 最后一个
arr[1:3] # 切片 [2, 3]
len(arr) # 长度
3 in arr # True
# 列表推导
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# 元组(tuple)— 有序、不可变
t = (1, 2, 3)
t[0] # 1
# t[0] = 0 ← 报错!元组不可修改
# 字典(dict)— 键值对、可变
d = {"name": "Alice", "age": 30}
d["name"] # 'Alice'
d.get("name") # 'Alice'
d.get("gender", "未知") # '未知'(不存在时返回默认值)
d["gender"] = "女" # 添加/修改
del d["age"] # 删除
"name" in d # True
d.keys() # dict_keys(['name', 'gender'])
d.values() # dict_values(['Alice', '女'])
d.items() # dict_items([('name', 'Alice'), ('gender', '女')])
# 字典推导
squares_dict = {x: x**2 for x in range(5)}
# 集合(set)— 无序、不重复
s = {1, 2, 3, 3, 3} # {1, 2, 3} 自动去重
s.add(4)
s.remove(2)
a = {1, 2, 3}
b = {2, 3, 4}
a & b # 交集 {2, 3}
a | b # 并集 {1, 2, 3, 4}
a - b # 差集 {1}控制流
python
# if-elif-else
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
# 三元表达式
age = 20
status = "成年" if age >= 18 else "未成年"
# match 语句(Python 3.10+,类似 switch)
def describe(value):
match value:
case 0:
return "零"
case 1 | 2 | 3:
return "小数字"
case int():
return "大数字"
case str():
return f"字符串: {value}"
case _:
return "其他"
# for 循环
for i in range(5): # 0 1 2 3 4
for i in range(2, 5): # 2 3 4
for i in range(0, 10, 2): # 0 2 4 6 8
for idx, item in enumerate(items):
print(idx, item)
for key, value in d.items():
print(key, value)
# while 循环
while count < 10:
count += 1
break # 跳出循环
continue # 跳过本次函数
python
# 基本函数
def greet(name):
return f"Hello {name}"
# 默认参数
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
# 关键字参数
greet(greeting="Hi", name="Alice")
# 可变参数
def sum_all(*args): # 任意数量位置参数 → 元组
return sum(args)
def create_user(**kwargs): # 任意数量关键字参数 → 字典
return kwargs
# 参数组合
def func(a, b, *args, c=10, **kwargs):
pass
# 类型注解
def add(a: int, b: int) -> int:
return a + b
# Lambda(匿名函数)
square = lambda x: x ** 2
list(map(lambda x: x * 2, [1, 2, 3]))
sorted(items, key=lambda x: x["age"])
# 装饰器
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f"耗时: {time.time() - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)类与面向对象
python
class Animal:
# 类变量(所有实例共享)
kingdom = "Animalia"
def __init__(self, name):
self.name = name # 实例变量
# 实例方法
def speak(self):
print(f"{self.name} 发出了声音")
# 静态方法(无需 self)
@staticmethod
def info():
return "这是一个动物类"
# 类方法(cls 参数)
@classmethod
def create_unknown(cls):
return cls("未知生物")
# 属性装饰器
@property
def description(self):
return f"动物: {self.name}"
# 继承
class Dog(Animal):
def __init__(self, name, breed="狗"):
super().__init__(name)
self.breed = breed
# 重写
def speak(self):
print(f"{self.name}: 汪汪!")
# 特殊方法
def __str__(self):
return f"Dog({self.name})"
def __len__(self):
return 4 # 四条腿
# 使用
dog = Dog("旺财")
dog.speak() # 旺财: 汪汪!
print(dog.description) # 动物: 旺财
print(str(dog)) # Dog(旺财)模块与包
python
# mymodule.py
def hello():
return "Hello from module"
if __name__ == "__main__":
# 只有在直接运行此文件时才会执行
print(hello())
# main.py — 导入
import mymodule
from mymodule import hello
from mymodule import hello as hi
# 包:包含 __init__.py 的目录
# mypackage/
# __init__.py
# module_a.py
# module_b.py
from mypackage import module_a文件 I/O
python
# 推荐:with 语句自动关闭
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部
lines = f.readlines() # 按行读取到列表
for line in f: # 逐行读取(大文件)
print(line)
# 写入
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
f.writelines(["line1\n", "line2\n"])
# 模式
# "r" 读取 "w" 写入(覆盖) "a" 追加 "rb" 二进制异常处理
python
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除零错误: {e}")
except (ValueError, TypeError) as e:
print(f"类型/值错误: {e}")
except Exception as e:
print(f"其他错误: {e}")
else:
print("没有发生异常")
finally:
print("总是执行")
# 抛出异常
raise ValueError("参数无效")
raise # 重新抛出当前异常
# 自定义异常
class BusinessError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code进阶特性
迭代器与生成器
python
# 生成器函数
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
next(fib) # 0
next(fib) # 1
next(fib) # 1
# 生成器表达式
squares = (x**2 for x in range(10))
# yield from
def chain(*iterables):
for it in iterables:
yield from it
list(chain([1, 2], [3, 4])) # [1, 2, 3, 4]上下文管理器
python
# 自定义上下文管理器
class ManagedFile:
def __enter__(self):
print("进入上下文")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("退出上下文")
# 使用 contextlib
from contextlib import contextmanager
@contextmanager
def managed_resource():
print("获取资源")
yield
print("释放资源")异步编程(asyncio)
python
import asyncio
async def fetch_data(url):
print(f"开始获取: {url}")
await asyncio.sleep(1) # 模拟网络请求
print(f"完成: {url}")
return f"data from {url}"
async def main():
# 顺序执行
# result = await fetch_data("http://example.com")
# 并发执行
tasks = [
fetch_data(f"http://api.example.com/{i}")
for i in range(5)
]
results = await asyncio.gather(*tasks)
return results
# 运行
results = asyncio.run(main())常用标准库
Python 自带"内置电池"(Batteries Included)哲学,标准库非常丰富:
| 模块 | 功能 |
|---|---|
os | 操作系统接口(文件/路径/环境变量) |
sys | Python 解释器交互(参数/退出/路径) |
json | JSON 编码解码 |
re | 正则表达式 |
math | 数学函数(sin/cos/sqrt/log) |
datetime | 日期时间处理 |
random | 随机数生成 |
collections | 扩展集合类型(Counter/defulatdict/OrderedDict) |
itertools | 迭代器工具(chain/cycle/permutations) |
functools | 高阶函数工具(reduce/lru_cache/partial) |
pathlib | 面向对象路径操作(Python 3.4+ 推荐替代 os.path) |
urllib | HTTP 请求 |
subprocess | 执行系统命令 |
threading | 多线程 |
multiprocessing | 多进程 |
unittest | 单元测试 |
logging | 日志记录 |
argparse | 命令行参数解析 |
dataclasses | 数据类(Python 3.7+ 简化类定义) |
typing | 类型提示支持 |
python
# 示例:常用标准库使用
import json
from datetime import datetime
from pathlib import Path
from collections import Counter
# JSON
data = json.loads('{"name": "Alice"}')
json.dumps(data, ensure_ascii=False, indent=2)
# 日期
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2024-12-25", "%Y-%m-%d")
# Path
p = Path("/data/logs/app.log")
p.parent # /data/logs
p.name # app.log
p.stem # app
p.suffix # .log
p.exists() # True
p.read_text() # 读取文本文件
# Counter
words = Counter("hello world hello".split())
# Counter({'hello': 2, 'world': 1})
words.most_common(1) # [('hello', 2)]
# dataclasses
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int = 18
email: str = ""
# 自动生成 __init__、__repr__、__eq__ 等第三方生态
Web 框架
| 框架 | 特点 | 适用场景 |
|---|---|---|
| Flask | 轻量、灵活、扩展丰富 | 小型项目、API 服务 |
| Django | 大而全(ORM/Admin/Auth) | 大型 Web 应用 |
| FastAPI | 高性能、异步、自动生成 API 文档 | RESTful API / 微服务 |
| Tornado | 异步非阻塞 | 长连接 / WebSocket |
数据科学与 AI
| 库 | 用途 |
|---|---|
| NumPy | 多维数组、数学运算 |
| Pandas | 数据分析、DataFrame |
| Matplotlib | 数据可视化 |
| Scikit-learn | 机器学习算法 |
| TensorFlow / PyTorch | 深度学习框架 |
| Jupyter | 交互式开发环境 |
其他常用
| 类别 | 库 |
|---|---|
| HTTP 请求 | requests(简洁)、httpx(异步) |
| 爬虫 | Scrapy、BeautifulSoup、Playwright |
| 数据库 ORM | SQLAlchemy、Django ORM、Tortoise ORM |
| 测试 | pytest、unittest |
| 任务队列 | Celery、RQ |
| 配置 | pydantic(数据校验)、python-dotenv |
| 命令行 | Click、Typer(FastAPI 作者出品) |
| 打包 | PyInstaller(打包 exe)、setuptools |
python
# pip install requests
import requests
res = requests.get("https://api.github.com")
res.json() # 解析 JSON 响应
res.status_code # 200
# pip install httpx(异步 HTTP)
import httpx
async with httpx.AsyncClient() as client:
res = await client.get("https://api.github.com")工具链
代码格式化
| 工具 | 说明 |
|---|---|
| Black | 最流行的格式化工具,零配置 |
| autopep8 | 基于 PEP 8 |
| isort | 自动排序 import |
bash
pip install black isort
black . # 格式化当前目录所有 .py 文件
isort . # 排序导入代码检查
| 工具 | 说明 |
|---|---|
| flake8 | 代码风格检查 |
| pylint | 更严格的代码分析 |
| mypy | 静态类型检查 |
| ruff | Rust 写的超快速 lint 工具(推荐) |
bash
pip install ruff
ruff check . # 检查所有文件
ruff format . # 格式化(ruff 也内置格式化)测试
python
# pytest(推荐)
# pip install pytest
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
# 运行
# pytest test_file.py -v调试
python
# 内置调试器
breakpoint() # Python 3.7+,自动进入 pdb 调试
import pdb; pdb.set_trace()
# 常用 pdb 命令
# n (next) 下一步
# s (step) 进入函数
# c (continue) 继续执行
# p (print) 打印变量
# q (quit) 退出应用场景
Web 开发
Django / Flask / FastAPI 构建 RESTful API、网站后端、CMS 系统。
数据科学与 AI
Python 是数据科学领域的第一语言:
- Pandas 处理表格数据
- Scikit-learn 做机器学习
- PyTorch / TensorFlow 做深度学习
- 大模型训练与推理(Hugging Face Transformers)
自动化脚本
系统管理、文件批量处理、数据迁移、定时任务。
爬虫
Scrapy 爬取网站数据、Requests + BeautifulSoup 简单抓取、Playwright 模拟浏览器。
DevOps
- Ansible — 配置管理
- SaltStack — 自动化运维
- Terraform CDK — 基础设施即代码
桌面应用
PyQt / PySide — 跨平台桌面 GUI。 Tkinter — 内置 GUI 库,适合简单界面。
游戏开发
Pygame — 2D 游戏开发库。
Python 的优缺点
优势
- 语法简洁 — 代码可读性极高,上手快
- 生态丰富 — PyPI 超过 50 万包,"内置电池"
- 多范式 — 面向对象、函数式、面向方面
- 胶水语言 — 轻松调用 C/C++ 库,适合作为上层调度
- 社区活跃 — 文档齐全、Stack Overflow 大量问答
- 跨平台 — 一次编写,到处运行
劣势
- 执行速度慢 — 解释型语言,CPU 密集型不占优势
- GIL 限制 — 全局解释器锁,多线程无法利用多核(多进程可绕过)
- 移动端弱 — 几乎没有原生移动应用生态
- 部署稍麻烦 — 需要运行时环境,打包体积大
Python 之禅
在 Python 交互式环境输入 import this 即可查看:
Beautiful is better than ugly. 优美优于丑陋
Explicit is better than implicit. 明确优于隐式
Simple is better than complex. 简单优于复杂
Complex is better than complicated. 复杂优于凌乱
Flat is better than nested. 扁平优于嵌套
Sparse is better than dense. 稀疏优于稠密
Readability counts. 可读性很重要
...