python知识

Python 速查手册

环境与包管理

镜像源配置

临时使用

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple <package>

永久配置 (推荐):

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

UV 同步 (Modern):

uv sync -i https://pypi.tuna.tsinghua.edu.cn/simple

虚拟环境

python -m venv .venv
# Windows
.venv\Scripts\activate
# Linux/Mac
source .venv/bin/activate

基础语法

推导式 (Comprehensions)

# List
squares = [x**2 for x in range(10) if x % 2 == 0]
# Dict
m = {x: x**2 for x in range(5)}
# Set
s = {x for x in [1, 2, 2, 3]}

字符串格式化 (f-string)

name = "Alice"
age = 30
print(f"Name: {name}, Age: {age:.2f}")

解包 (Unpacking)

a, *b, c = [1, 2, 3, 4, 5]  # a=1, b=[2,3,4], c=5
d = {**dict1, **dict2}      # 合并字典

typing (类型提示)

Python 的静态类型检查系统,用于提升代码可读性与 IDE 智能提示,不影响运行时。

1. 基础类型与函数

最基本的变量与函数签名标注。

# 变量
count: int = 0
is_valid: bool = True

# 函数:参数 -> 返回值
def greet(name: str) -> str:
    return f"Hello, {name}"

2. 常用容器

Python 3.9+ 推荐直接使用内置类型(list, dict 等)。

# 列表与集合
names: list[str] = ["Alice", "Bob"]
ids: set[int] = {1, 2, 3}

# 字典:dict[KeyType, ValueType]
scores: dict[str, int] = {"Math": 90}

# 元组:tuple[T1, T2] 或 tuple[T, ...] (不定长)
pair: tuple[int, int] = (10, 20)
row: tuple[str, ...] = ("a", "b", "c")

3. 多态与空值 (Union & Optional)

处理多种类型或可能为 None 的情况。

from typing import Union, Optional

# 可能是 int 或 float
def double(x: Union[int, float]) -> float:
    return x * 2

# 可能是 str 或 None (常用)
def find_user(uid: int) -> Optional[str]:
    return "Alice" if uid == 1 else None

4. 字面量 (Literal)

强制变量只能取特定的值,常用于配置选项。

from typing import Literal

Mode = Literal['r', 'w', 'a']

def open_file(path: str, mode: Mode = 'r'):
    pass

5. 结构化字典 (TypedDict)

比普通 dict 更严格,明确字段名与类型,常用于 JSON 数据。

from typing import TypedDict

class User(TypedDict):
    id: int
    name: str
    is_admin: bool

u: User = {"id": 1, "name": "Alice", "is_admin": False}

6. 泛型 (TypeVar)

让函数或类支持多种类型,同时保持类型约束。

from typing import TypeVar

T = TypeVar("T")  # 定义泛型变量

def first(items: list[T]) -> T:
    return items[0]

n = first([1, 2])      # 推断为 int
s = first(["a", "b"])  # 推断为 str

7. 任意类型 (Any)

逃生舱:当类型难以描述或暂时不想处理时使用。

from typing import Any

def debug(data: Any) -> None:
    print(data)

装饰器 (Decorators)

装饰器本质上是一个接收函数作为参数并返回新函数的高阶函数。它允许在不修改原函数代码的情况下,动态地增加功能。

1. 基础模板

使用 @wraps 保留原函数元数据(如 __name__, __doc__),这对调试和文档生成至关重要。

from functools import wraps
import time

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # 1. 函数执行前的操作
        print(f"[Log] Calling {func.__name__}...")
        
        # 2. 执行原函数
        result = func(*args, **kwargs)
        
        # 3. 函数执行后的操作
        print(f"[Log] Finished {func.__name__}.")
        return result
    return wrapper

@my_decorator
def add(x, y):
    """Add two numbers."""
    return x + y

# add.__name__ 依然是 'add',而不是 'wrapper'

2. 带参数装饰器

当装饰器本身需要参数时(如重试次数、超时时间),需要三层嵌套结构。

def repeat(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(times):
                print(f"Run {i+1}/{times}")
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def greet():
    print("Hello")

3. 常见使用场景

(1) 计时 (Timing)

用于性能分析。

def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f}s")
        return result
    return wrapper

(2) 缓存 (Caching)

避免重复计算,Python 内置了 lru_cache

from functools import lru_cache

@lru_cache(maxsize=128)
def fib(n):
    if n < 2: return n
    return fib(n-1) + fib(n-2)

(3) 权限校验 (Authentication)

Web 开发中常用。

def require_admin(func):
    @wraps(func)
    def wrapper(user, *args, **kwargs):
        if not user.is_admin:
            raise PermissionError("Admin access required")
        return func(user, *args, **kwargs)
    return wrapper

(4) 异常捕获与重试 (Retry)

增强代码健壮性。

def retry(max_retries=3):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print(f"Retrying due to: {e}")
            raise Exception("Max retries exceeded")
        return wrapper
    return decorator

文件与路径

pathlib (推荐)

面向对象的文件路径处理。

from pathlib import Path

p = Path('/path/to/file.txt')
p.exists()
p.name          # file.txt
p.parent        # /path/to
p.read_text()   # 读取内容
p.write_text("hello") # 写入内容

glob (文件匹配)

import glob
# 匹配所有txt
files = glob.glob("./*.txt")
# 排除特定文件
files = glob.glob("./*[!.txt]")

json 读写

import json

# Load
with open('data.json', 'r') as f:
    data = json.load(f)

# Dump
with open('data.json', 'w') as f:
    json.dump(data, f, indent=4, ensure_ascii=False)

面向对象 (OOP)

魔术方法

  • __str__: 用户友好的字符串表示 (print(obj)).
  • __repr__: 开发者友好的字符串表示 (调试用).
  • str(obj) 查找顺序: __str__ -> __repr__.

数据类 (Dataclass)

快速定义只包含数据的类。

from dataclasses import dataclass, field
from typing import List

@dataclass
class Point:
    x: float
    y: float

p = Point(1.5, 2.5)
print(p) # Point(x=1.5, y=2.5)

# 特殊容器默认值 (Mutable Defaults)
# 对于 List/Dict 等可变类型,直接赋值 (e.g. x: list = []) 会报错。
# 必须使用 field(default_factory=...) 来确保每个实例拥有独立的容器。
@dataclass
class Student:
    name: str
    # 默认为空列表
    grades: List[int] = field(default_factory=list)
    # 默认为包含初始值的字典
    info: dict = field(default_factory=lambda: {"active": True})

s = Student("Alice")
s.grades.append(100)
print(s) # Student(name='Alice', grades=[100], info={'active': True})

抽象基类 (ABC)

强制子类实现特定方法。

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rect(Shape):
    def area(self):
        return 100

常用库

collections

from collections import defaultdict, Counter

# Defaultdict
d = defaultdict(int)
d['a'] += 1

# Counter
c = Counter(['a', 'b', 'a'])
print(c.most_common(1))

datetime

from datetime import datetime, timedelta

now = datetime.now()
yesterday = now - timedelta(days=1)
s = now.strftime("%Y-%m-%d %H:%M:%S")

学习资源