附录

附录 A 常用语言与语法速查表

本节最后更新:2026-05-11
验证环境:无(语法速查——参考章节)

本节是快速参考,不是教程。如果你完全没接触过这些语言,建议先通过 Vibe Coding 实际体验,遇到语法问题时回来查阅。

A.1 JavaScript / TypeScript 核心语法

A.1.1 变量声明与作用域

// var —— 函数作用域,存在变量提升问题,不再推荐使用
var name = "Alice";
function example() {
  console.log(name); // undefined(变量提升)
  var name = "Bob";
}

// let —— 块级作用域,可重新赋值
let count = 0;
count = 1;
if (true) {
  let x = 10;
}
// console.log(x); // ❌ x is not defined

// const —— 块级作用域,不可重新赋值(推荐默认使用)
const pi = 3.14;
// pi = 3.1415; // ❌ 不可重新赋值

const user = { name: "Alice" };
user.name = "Bob"; // ✅ 对象内容可以修改(引用不变)

// 暂时性死区(TDZ)
// console.log(a); // ❌ Cannot access 'a' before initialization
let a = 10;

// 解构赋值中的 TDZ
function test({ a = 1, b = 2 } = {}) {
  console.log(a, b);
}
test(); // 1, 2

A.1.2 函数定义

// 传统函数声明(存在函数提升)
function add(a, b) {
  return a + b;
}

// 函数表达式
const multiply = function(a, b) {
  return a * b;
};

// 箭头函数(现代JS最常用)
const divide = (a, b) => a / b;
const square = x => x * x;

// 带返回值的箭头函数(多行)
const greet = (name) => {
  const message = `Hello, ${name}!`;
  return message;
};

// 默认参数
const introduce = (name, age = 18) => {
  return `${name} is ${age} years old`;
};

// 可选参数
const sayHello = (name) => {
  return `Hello, ${name || "Guest"}!`;
};

// 剩余参数
const sumAll = (...numbers) => {
  return numbers.reduce((sum, num) => sum + num, 0);
};

// 异步函数
async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

// 立即执行函数表达式(IIFE)
(function() {
  console.log("立即执行");
})();

// 箭头函数IIFE
(() => {
  console.log("箭头函数IIFE");
})();

A.1.3 解构赋值与展开运算符

// 对象解构
const user = { name: "Alice", age: 30, city: "Beijing" };
const { name, age } = user;
const { name: userName, age: userAge } = user; // 重命名

// 默认值
const { name, age = 18, country = "China" } = user;

// 嵌套解构
const nested = { user: { name: "Alice", address: { city: "Beijing" } } };
const { user: { name, address: { city } } } = nested;

// 数组解构
const colors = ["red", "green", "blue", "yellow"];
const [first, second, third] = colors;
const [, , thirdColor] = colors; // 跳过前两个

// 剩余运算符(收集剩余元素)
const [head, ...rest] = colors; // head="red", rest=["green", "blue", "yellow"]

// 展开运算符(展开数组/对象)
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

// 合并对象(后面对象覆盖前面)
const merged = { ...obj1, ...obj2 };

// 函数参数展开
const nums = [1, 2, 3];
Math.max(...nums); // 3

// 解构配合展开
const { name, ...rest } = user; // rest = { age: 30, city: "Beijing" }

// 函数参数解构
function printUser({ name, age }) {
  console.log(`${name} is ${age}`);
}
printUser(user);

A.1.4 数组方法速查

方法作用返回值是否修改原数组
map()转换每个元素新数组
filter()过滤元素新数组
reduce()累积计算任意值
find()查找第一个匹配元素元素/undefined
findIndex()查找第一个匹配索引索引/-1
some()是否有元素满足条件boolean
every()是否所有元素满足条件boolean
includes()是否包含指定元素boolean
concat()合并数组新数组
slice()截取子数组新数组
push()末尾添加元素新长度
pop()末尾删除元素被删元素
shift()开头删除元素被删元素
unshift()开头添加元素新长度
splice()插入/删除元素被删元素数组
sort()排序原数组引用
reverse()反转数组原数组引用
flat()扁平化数组新数组
flatMap()映射后扁平化新数组
fill()填充数组原数组
indexOf()查找元素索引索引/-1
lastIndexOf()从后查找元素索引索引/-1
join()数组转字符串字符串
toString()数组转字符串字符串
// 常用数组操作示例
const numbers = [1, 2, 3, 4, 5];

// map - 转换
const doubled = numbers.map(x => x * 2); // [2, 4, 6, 8, 10]

// filter - 过滤
const evens = numbers.filter(x => x % 2 === 0); // [2, 4]

// reduce - 累积
const sum = numbers.reduce((acc, x) => acc + x, 0); // 15

// find - 查找
const found = numbers.find(x => x > 3); // 4

// flat - 扁平化
const nested = [1, [2, [3, [4]]]];
const flattened = nested.flat(2); // [1, 2, 3, [4]]

// flatMap - 映射并扁平化
const sentences = ["Hello world", "Goodbye world"];
const words = sentences.flatMap(s => s.split(" ")); // ["Hello", "world", "Goodbye", "world"]

// fill - 填充
const filled = new Array(5).fill(0); // [0, 0, 0, 0, 0]

A.1.5 Promise 和异步编程

// Promise 基础
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
    // 或 reject(new Error("failed"));
  }, 1000);
});

promise.then(result => console.log(result))
       .catch(error => console.error(error));

// Promise.all(全部完成)
const promises = [fetch('/api/users'), fetch('/api/posts')];
Promise.all(promises)
  .then(responses => Promise.all(responses.map(r => r.json())))
  .then(data => console.log(data));

// Promise.allSettled(全部完成或失败)
Promise.allSettled(promises)
  .then(results => results.forEach(r => console.log(r.status)));

// Promise.race(第一个完成)
Promise.race([
  fetch('/api/data'),
  new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 5000))
])
.then(data => console.log(data))
.catch(err => console.error(err));

// Promise.any(第一个成功)
Promise.any([
  Promise.reject('error1'),
  Promise.resolve('success'),
  Promise.reject('error2')
])
.then(result => console.log(result)); // "success"

// async/await(现代异步写法)
async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch failed:', error);
    throw error;
  }
}

// 并行执行多个异步操作
async function fetchMultiple() {
  const [users, posts] = await Promise.all([
    fetch('/api/users').then(r => r.json()),
    fetch('/api/posts').then(r => r.json())
  ]);
  return { users, posts };
}

// 串行执行
async function fetchSequentially() {
  const users = await fetch('/api/users').then(r => r.json());
  const posts = await fetch('/api/posts').then(r => r.json());
  return { users, posts };
}

// 异步迭代
async function processItems(items) {
  for await (const item of items) {
    await process(item);
  }
}

A.1.6 TypeScript 类型系统

// 基础类型
const name: string = "Alice";
const age: number = 30;
const isActive: boolean = true;
const list: string[] = ["a", "b", "c"];
const tuple: [string, number] = ["Alice", 30]; // 元组

// 接口定义
interface User {
  id: string;           // 必填字段
  name: string;
  email: string;
  age?: number;         // 可选字段(?标记)
  readonly createdAt: Date;  // 只读字段
}

// 接口继承
interface Admin extends User {
  permissions: string[];
}

// 接口声明合并
interface User {
  avatar?: string;  // 可以添加新属性
}

// 类型别名
type Status = "active" | "inactive" | "pending";
type Point = { x: number; y: number };
type ID = string | number;

// 联合类型与交叉类型
type Result<T, E> = { success: true; data: T } | { success: false; error: E };
type ReadonlyUser = Readonly<User>;  // 内置工具类型
type PartialUser = Partial<User>;    // 全部可选
type PickUser = Pick<User, "name" | "email">; // 挑选字段
type OmitUser = Omit<User, "password">; // 排除字段

// 泛型
interface ApiResponse<T> {
  data: T;
  success: boolean;
  message?: string;
}

// 泛型函数
function identity<T>(arg: T): T {
  return arg;
}

// 泛型类
class Container<T> {
  private items: T[] = [];
  add(item: T): void {
    this.items.push(item);
  }
  get(index: number): T | undefined {
    return this.items[index];
  }
}

// 泛型约束
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

// 条件类型
type NonNullable<T> = T extends null | undefined ? never : T;
type ExtractArray<T> = T extends (infer U)[] ? U : never;
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

// 模板字面量类型
type EventName<T extends string> = `${T}Changed`;
type UserEvents = EventName<"name" | "email">; // "nameChanged" | "emailChanged"

// 类型守卫
function isString(value: unknown): value is string {
  return typeof value === "string";
}

// 断言函数
function assertIsNumber(value: unknown): asserts value is number {
  if (typeof value !== "number") {
    throw new Error("Not a number");
  }
}

// 索引类型
type Keys = keyof User; // "id" | "name" | "email" | "age" | "createdAt"
type Values = User[keyof User]; // string | number | Date | undefined

// 映射类型
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

type Partial<T> = {
  [P in keyof T]?: T[P];
};

A.1.7 类与面向对象

// 类定义
class Person {
  // 私有属性
  private _name: string;
  
  // 构造函数
  constructor(name: string) {
    this._name = name;
  }
  
  // Getter
  get name(): string {
    return this._name;
  }
  
  // Setter
  set name(newName: string) {
    if (newName.length > 0) {
      this._name = newName;
    }
  }
  
  // 方法
  greet(): string {
    return `Hello, ${this._name}!`;
  }
}

// 继承
class Student extends Person {
  constructor(name: string, public studentId: string) {
    super(name);
  }
  
  study(subject: string): string {
    return `${this.name} is studying ${subject}`;
  }
}

// 抽象类
abstract class Shape {
  abstract getArea(): number;
  
  getDescription(): string {
    return `This shape has area: ${this.getArea()}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }
  
  getArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

// 接口实现
interface Printable {
  print(): void;
}

class Document implements Printable {
  print(): void {
    console.log("Printing document...");
  }
}

// 静态成员
class MathUtils {
  static PI = 3.14159;
  
  static calculateArea(radius: number): number {
    return this.PI * radius ** 2;
  }
}

// 私有字段(#语法)
class Counter {
  #count = 0;
  
  increment(): void {
    this.#count++;
  }
  
  get count(): number {
    return this.#count;
  }
}

// 方法重载
class Calculator {
  add(a: number, b: number): number;
  add(a: string, b: string): string;
  add(a: number | string, b: number | string): number | string {
    if (typeof a === "number" && typeof b === "number") {
      return a + b;
    }
    return `${a}${b}`;
  }
}

A.1.8 模块化与ESM

// 导出
export const PI = 3.14;
export function add(a: number, b: number): number {
  return a + b;
}
export class Calculator {}
export type Status = "active" | "inactive";

// 默认导出
export default function greet(name: string): string {
  return `Hello, ${name}!`;
}

// 导入
import { PI, add, Calculator } from "./math";
import Greet from "./greet";
import * as math from "./math";

// 动态导入
async function loadModule() {
  const module = await import("./lazy");
  module.doSomething();
}

// 命名空间导入
import { default as Greet, PI as MathPI } from "./math";

// 重新导出
export { add as sum } from "./math";
export * from "./utils";

// 导入类型(仅类型导入)
import type { User } from "./types";

// 导出类型
export type { Status };

A.1.9 装饰器(Decorators)

// 类装饰器
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return `Hello, ${this.greeting}`;
  }
}

// 方法装饰器
function enumerable(value: boolean) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.enumerable = value;
  };
}

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  
  @enumerable(false)
  greet() {
    return `Hello, ${this.greeting}`;
  }
}

// 属性装饰器
function format(formatString: string) {
  return function (target: any, propertyKey: string) {
    let value = target[propertyKey];
    
    const getter = function () {
      return formatString.replace("%s", value);
    };
    
    const setter = function (newVal: string) {
      value = newVal;
    };
    
    Object.defineProperty(target, propertyKey, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true
    });
  };
}

class Greeter {
  @format("Hello, %s!")
  greeting: string;
  
  constructor(message: string) {
    this.greeting = message;
  }
}

// 参数装饰器
function validate(target: any, propertyKey: string, parameterIndex: number) {
  console.log(`Validating parameter at index ${parameterIndex}`);
}

class UserService {
  createUser(@validate name: string, @validate age: number) {
    // ...
  }
}

A.2 Python 常用模式

A.2.1 变量与数据结构

# 基本类型
name = "Alice"
age = 30
is_active = True
pi = 3.14
big_num = 10**18  # 任意精度整数

# 列表(list)- 可变数组
items = [1, 2, 3]
items.append(4)      # 添加元素
items.insert(0, 0)   # 插入元素
items.remove(2)      # 删除元素
items.pop()          # 弹出最后一个元素
items.extend([5, 6]) # 扩展列表

# 字典(dict)- 键值对
user = {"name": "Alice", "age": 30}
user["city"] = "Beijing"  # 添加键值对
del user["age"]          # 删除键值对
print(user.get("name", "Unknown"))  # 安全获取
keys = user.keys()       # 获取所有键
values = user.values()   # 获取所有值
items = user.items()     # 获取所有键值对

# 元组(tuple)- 不可变序列
point = (10, 20)
single = (5,)  # 单元素元组必须加逗号

# 集合(set)- 无序不重复
unique = {1, 2, 3, 3, 3}  # {1, 2, 3}
unique.add(4)
unique.remove(2)
union = unique | {3, 4, 5}  # 并集
intersection = unique & {2, 3}  # 交集
difference = unique - {3}  # 差集

# 冻结集合(frozenset)- 不可变集合
fs = frozenset([1, 2, 3])

# 字符串操作
s = "Hello, World!"
s.upper()           # "HELLO, WORLD!"
s.lower()           # "hello, world!"
s.strip()           # 去除首尾空白
s.replace("World", "Python")  # "Hello, Python!"
s.split(",")        # ["Hello", " World!"]
", ".join(["a", "b", "c"])  # "a, b, c"
s.startswith("Hello")  # True
s.endswith("!")        # True
s.find("World")        # 7

A.2.2 列表推导式与生成器

# 基础列表推导
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 带条件过滤
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# 嵌套推导(矩阵转置)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

# 集合推导
unique_squares = {x**2 for x in [-1, 0, 1, 2]}
# {0, 1, 4}

# 字典推导
squared_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 生成器表达式(内存高效)
gen = (x**2 for x in range(1000000))  # 不立即计算

# 生成器函数
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)  # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

# 无限生成器
def infinite_counter(start=0):
    while True:
        yield start
        start += 1

# 迭代器协议
class Counter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current < self.limit:
            value = self.current
            self.current += 1
            return value
        raise StopIteration

A.2.3 函数与参数

def add(a: int, b: int) -> int:
    """返回两个数的和"""
    return a + b

# 默认参数
def greet(name: str = "World") -> str:
    return f"Hello, {name}!"

# 可变位置参数(*args)
def sum_all(*args: int) -> int:
    return sum(args)

sum_all(1, 2, 3, 4)  # 10

# 可变关键字参数(**kwargs)
def create_user(**kwargs):
    return kwargs

create_user(name="Alice", age=30)  # {"name": "Alice", "age": 30}

# 解包参数
nums = [1, 2, 3]
sum_all(*nums)  # 相当于 sum_all(1, 2, 3)

config = {"host": "localhost", "port": 5432}
# connect(**config)  # 相当于 connect(host="localhost", port=5432)

# Lambda 函数
square = lambda x: x ** 2

# 高阶函数
def apply(func, value):
    return func(value)

apply(lambda x: x * 2, 5)  # 10

# 匿名函数作为参数
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))  # [1, 4, 9, 16]
evens = list(filter(lambda x: x % 2 == 0, numbers))  # [2, 4]

# 函数注解
def calculate(
    x: int,
    y: int,
    operation: str = "add"
) -> int:
    """
    计算两个数的运算结果
    
    Args:
        x: 第一个数字
        y: 第二个数字
        operation: 运算类型,可选值: "add", "subtract", "multiply", "divide"
    
    Returns:
        运算结果
    """
    if operation == "add":
        return x + y
    elif operation == "subtract":
        return x - y
    elif operation == "multiply":
        return x * y
    elif operation == "divide":
        return x / y
    else:
        raise ValueError(f"Unknown operation: {operation}")

A.2.4 类与面向对象

class Person:
    # 类属性(所有实例共享)
    species = "Homo sapiens"
    
    # 初始化方法
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age
    
    # 实例方法
    def greet(self) -> str:
        return f"Hello, my name is {self.name}"
    
    # 类方法
    @classmethod
    def from_birth_year(cls, name: str, birth_year: int):
        current_year = 2024
        return cls(name, current_year - birth_year)
    
    # 静态方法
    @staticmethod
    def is_adult(age: int) -> bool:
        return age >= 18

# 创建实例
person = Person("Alice", 30)
person.greet()  # "Hello, my name is Alice"

# 继承
class Student(Person):
    def __init__(self, name: str, age: int, student_id: str):
        super().__init__(name, age)
        self.student_id = student_id
    
    def study(self, subject: str) -> str:
        return f"{self.name} is studying {subject}"

# 特殊方法(魔术方法)
class Vector:
    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    
    def __repr__(self) -> str:
        return f"Vector({self.x}, {self.y})"
    
    def __len__(self):
        return int((self.x**2 + self.y**2)**0.5)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v1 + v2  # Vector(4, 6)
v1 * 2   # Vector(2, 4)

# 属性装饰器
class Product:
    def __init__(self, name: str, price: float):
        self.name = name
        self._price = price
    
    @property
    def price(self) -> float:
        return self._price
    
    @price.setter
    def price(self, value: float):
        if value < 0:
            raise ValueError("Price cannot be negative")
        self._price = value

# 抽象基类
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def get_area(self) -> float:
        pass
    
    @abstractmethod
    def get_perimeter(self) -> float:
        pass

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius
    
    def get_area(self) -> float:
        return 3.14159 * self.radius ** 2
    
    def get_perimeter(self) -> float:
        return 2 * 3.14159 * self.radius

A.2.5 装饰器

# 基础装饰器
def log_function(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_function
def add(a, b):
    return a + b

add(2, 3)
# Output:
# Calling add with args=(2, 3), kwargs={}
# add returned 5

# 带参数的装饰器
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            results = []
            for _ in range(times):
                results.append(func(*args, **kwargs))
            return results
        return wrapper
    return decorator

@repeat(times=3)
def greet(name):
    return f"Hello, {name}!"

greet("Alice")  # ["Hello, Alice!", "Hello, Alice!", "Hello, Alice!"]

# 保留元数据的装饰器
import functools

def log_decorator(func):
    @functools.wraps(func)  # 保留原函数元数据
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_decorator
def add(a, b):
    """Return sum of two numbers"""
    return a + b

# 装饰器类
class CountCalls:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func
        self.count = 0
    
    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call {self.count} of {self.func.__name__}")
        return self.func(*args, **kwargs)

@CountCalls
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 多个装饰器叠加
@log_decorator
@repeat(times=2)
def say_hello():
    return "Hello!"

# 装饰器用于类型检查
def type_check(*arg_types):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args):
            for arg, expected_type in zip(args, arg_types):
                if not isinstance(arg, expected_type):
                    raise TypeError(f"Expected {expected_type}, got {type(arg)}")
            return func(*args)
        return wrapper
    return decorator

@type_check(int, int)
def multiply(a, b):
    return a * b

A.2.6 上下文管理器

# 使用 with 语句
with open("file.txt", "r") as f:
    content = f.read()
# 文件自动关闭

# 自定义上下文管理器(类方式)
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        elapsed = time.time() - self.start
        print(f"Elapsed time: {elapsed:.2f}s")
        return False

with Timer():
    for _ in range(1000000):
        pass

# 自定义上下文管理器(装饰器方式)
from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    try:
        yield
    finally:
        elapsed = time.time() - start
        print(f"Elapsed: {elapsed:.2f}s")

with timer():
    pass

# 嵌套上下文管理器
with open("input.txt", "r") as infile, open("output.txt", "w") as outfile:
    content = infile.read()
    outfile.write(content)

# 自定义资源管理
class DatabaseConnection:
    def __init__(self, db_url):
        self.db_url = db_url
        self.connection = None
    
    def __enter__(self):
        self.connection = self.connect()
        return self.connection
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.connection:
            self.connection.close()
        return False  # 不抑制异常
    
    def connect(self):
        print(f"Connecting to {self.db_url}")
        return {"connection": "active"}

# 使用
with DatabaseConnection("postgresql://localhost/mydb") as conn:
    print("Using connection:", conn)

# 使用 contextmanager 装饰器创建临时文件
from contextlib import contextmanager
import tempfile
import os

@contextmanager
def temp_file():
    fd, path = tempfile.mkstemp()
    try:
        yield path
    finally:
        os.close(fd)
        os.remove(path)

with temp_file() as filepath:
    print(f"Working with temp file: {filepath}")

A.2.7 常用标准库

模块用途常用功能
os操作系统接口文件/目录操作、环境变量
sys系统参数与函数命令行参数、退出码
jsonJSON 序列化dump/load, dumps/loads
datetime日期时间处理datetime, date, time
re正则表达式匹配、替换、分割
collections数据结构defaultdict, OrderedDict, Counter
itertools迭代工具循环、组合、排列
functools函数工具partial, lru_cache, reduce
asyncio异步编程协程、事件循环
unittest测试框架TestCase, mock
logging日志记录日志级别、格式、处理器
argparse命令行参数解析参数定义、帮助信息
pathlib文件路径操作面向对象的路径处理
urllibURL 处理解析、请求
hashlib哈希函数md5, sha256

A.2.8 Python 异步编程

import asyncio

# 基础协程
async def fetch_data(url):
    print(f"Fetching {url}")
    await asyncio.sleep(1)  # 模拟IO操作
    return {"url": url, "data": "sample"}

# 并发执行多个协程
async def main():
    # 方式1: asyncio.gather
    results = await asyncio.gather(
        fetch_data("https://api.example.com/users"),
        fetch_data("https://api.example.com/posts"),
        fetch_data("https://api.example.com/comments")
    )
    print(results)
    
    # 方式2: 创建任务
    task1 = asyncio.create_task(fetch_data("https://api.example.com/a"))
    task2 = asyncio.create_task(fetch_data("https://api.example.com/b"))
    
    await task1
    await task2

# 运行事件循环
asyncio.run(main())

# 带超时的等待
async def fetch_with_timeout(url, timeout=5):
    try:
        return await asyncio.wait_for(fetch_data(url), timeout=timeout)
    except asyncio.TimeoutError:
        print(f"Timeout fetching {url}")
        return None

# 并发限制(Semaphore)
async def limited_fetch(url, semaphore):
    async with semaphore:
        return await fetch_data(url)

async def fetch_all(urls):
    semaphore = asyncio.Semaphore(10)  # 最多10个并发
    tasks = [limited_fetch(url, semaphore) for url in urls]
    return await asyncio.gather(*tasks)

# 异步迭代器
async def async_range(n):
    for i in range(n):
        await asyncio.sleep(0.1)
        yield i

async def iterate():
    async for num in async_range(5):
        print(num)

# 异步生成器
async def async_generator():
    for i in range(10):
        await asyncio.sleep(0.1)
        yield i * 2

# 任务取消
async def long_running_task():
    try:
        for i in range(10):
            await asyncio.sleep(1)
            print(f"Task running: {i}")
    except asyncio.CancelledError:
        print("Task was cancelled")
        raise

async def cancel_task():
    task = asyncio.create_task(long_running_task())
    await asyncio.sleep(3)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("Task cancellation confirmed")

A.3 HTML / CSS 关键布局速览

A.3.1 HTML 文档基础结构

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="页面描述">
  <meta name="keywords" content="关键词1, 关键词2">
  <meta name="author" content="作者名">
  <title>页面标题</title>
  <link rel="stylesheet" href="style.css">
  <link rel="icon" href="favicon.ico" type="image/x-icon">
</head>
<body>
  <header>页眉</header>
  <nav>导航</nav>
  <main>
    <article>主要内容</article>
    <aside>侧边栏</aside>
  </main>
  <footer>页脚</footer>
  <script src="app.js" defer></script>
</body>
</html>

A.3.2 常用语义标签

标签语义常用属性
页面/区块头部
导航链接
主要内容(唯一)
独立内容区块
内容分区
侧边内容
页面/区块底部
链接href, target, rel
图片src, alt, width, height
输入框type, name, value, placeholder
按钮type, disabled
表单action, method, enctype
标签for