python的核心知识点

发布时间:2026/8/5 6:44:51
python的核心知识点 一、基础语法与数据类型1. 程序结构与交互式环境python#!/usr/bin/env python3 # -*- coding: utf-8 -*- Python 程序结构演示 # 1. 注释方式 # 单行注释 多行注释文档字符串 # 2. 模块导入 import sys import math from datetime import datetime from typing import List, Optional # 3. 主程序入口Python特有 if __name__ __main__: print(程序开始执行) print(fPython版本: {sys.version}) print(f当前时间: {datetime.now()}) # 4. 交互式输入输出 name input(请输入你的名字: ) print(f你好, {name}!)2. 变量与数据类型python# Python是动态强类型语言变量无需声明类型但类型在运行时确定 # ---------- 数字类型 ---------- integer 42 # int任意精度 float_num 3.14159 # float双精度 complex_num 3 4j # complex复数 long_int 10**100 # 大整数无溢出 binary 0b1010 # 二进制 octal 0o755 # 八进制 hexadecimal 0xFF # 十六进制 # ---------- 布尔类型 ---------- is_true True is_false False bool_from_int bool(1) # True bool_from_empty bool([]) # False空容器为False # ---------- 字符串 ---------- str1 Hello str2 World str3 多行 字符串 str4 Hello World # 拼接 str5 f你好, {name} # f-string格式化字符串 str6 Hello %s % World # %格式化旧式 str7 Hello {}.format(World) # format方法 # ---------- 类型转换 ---------- int(123) # 字符串转整数 str(123) # 整数转字符串 float(3.14) # 字符串转浮点 list(abc) # [a, b, c] # ---------- 类型检查 ---------- print(type(integer)) # class int print(isinstance(3.14, float)) # True print(isinstance([1,2], list)) # True3. 容器数据类型核心python# ---------- 列表List- 可变有序 ---------- fruits [apple, banana, orange] fruits.append(grape) # 末尾添加 fruits.insert(1, pear) # 指定位置插入 fruits.remove(banana) # 删除元素 popped fruits.pop() # 弹出末尾元素 fruits[0] pineapple # 修改 sliced fruits[1:3] # 切片返回新列表 list_comp [x**2 for x in range(10)] # 列表推导式 print(fruits) # [pineapple, pear, orange] # ---------- 元组Tuple- 不可变有序 ---------- coord (10, 20) x, y coord # 解包 single_tuple (1,) # 单元素元组注意逗号 tuple_from_list tuple([1, 2, 3]) # ---------- 字典Dict- 键值对无序3.7有序 ---------- person { name: Alice, age: 30, city: Beijing } person[age] 31 # 修改 person[email] alicemail # 新增 name person.get(name) # 安全获取 keys person.keys() # 所有键 values person.values() # 所有值 items person.items() # 所有键值对 del person[city] # 删除 # 字典推导式 squares {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} # ---------- 集合Set- 无序不重复 ---------- set1 {1, 2, 3, 3, 4} # {1, 2, 3, 4}自动去重 set2 set([3, 4, 5, 6]) union set1 | set2 # 并集 {1,2,3,4,5,6} intersection set1 set2 # 交集 {3,4} difference set1 - set2 # 差集 {1,2} symmetric_diff set1 ^ set2 # 对称差 {1,2,5,6} set1.add(10) # 添加 set1.remove(1) # 删除不存在会报错 set1.discard(99) # 删除不存在不报错 # ---------- 不可变集合Frozenset ---------- immutable_set frozenset([1, 2, 3]) # 可哈希可用作字典键二、运算符与表达式python# ---------- 算术运算符 ---------- print(10 3) # 13 print(10 - 3) # 7 print(10 * 3) # 30 print(10 / 3) # 3.3333333333333335浮点除法 print(10 // 3) # 3整除 print(10 % 3) # 1取余 print(2 ** 3) # 8幂运算 # ---------- 比较运算符 ---------- print(10 3) # True print(10 10) # True print(10 ! 3) # True print(10 10) # True # ---------- 逻辑运算符短路求值 ---------- a True b False print(a and b) # False print(a or b) # True print(not a) # False # 短路示例 def expensive(): print(执行了expensive函数) return True result False and expensive() # expensive不会执行短路 result True or expensive() # expensive不会执行 # ---------- 身份运算符比较内存地址 ---------- x [1, 2, 3] y [1, 2, 3] z x print(x is z) # True指向同一对象 print(x is y) # False不同对象但值相同 print(x y) # True值相等 print(x is not y) # True # ---------- 成员运算符 ---------- fruits [apple, banana] print(apple in fruits) # True print(grape not in fruits) # True # ---------- 赋值运算符链式 ---------- a b c 10 a, b b, a # 交换变量Python特有 # ---------- 海象运算符Walrus Operator, Python 3.8 ---------- # 赋值表达式在表达式中赋值 if (n : len([1, 2, 3])) 2: print(f列表长度: {n}) # n被赋值并使用三、流程控制python# ---------- if-elif-else ---------- score 85 if score 90: grade A elif score 80: grade B elif score 70: grade C else: grade D print(f成绩: {grade}) # 三元表达式 age 20 status 成年 if age 18 else 未成年 # ---------- for循环 ---------- # 遍历可迭代对象 for fruit in [apple, banana, orange]: print(fruit) # 使用range for i in range(5): # 0-4 print(i) for i in range(2, 10, 2): # 2,4,6,8 print(i) # 遍历字典 person {name: Alice, age: 30} for key, value in person.items(): print(f{key}: {value}) # enumerate获取索引 for idx, value in enumerate([a, b, c]): print(f索引{idx}: {value}) # zip并行遍历 names [Alice, Bob, Charlie] ages [25, 30, 35] for name, age in zip(names, ages): print(f{name} {age}岁) # ---------- while循环 ---------- count 0 while count 5: print(count) count 1 # ---------- break, continue, else ---------- for i in range(10): if i 5: break # 提前退出 if i % 2 0: continue # 跳过本次迭代 print(i) # for-else循环正常结束才执行else for i in range(3): print(i) else: print(循环正常结束) # 会执行 for i in range(3): if i 1: break else: print(不会执行) # break导致不执行四、函数与作用域python# ---------- 函数定义 ---------- def greet(name: str, age: int 18) - str: 带类型注解的函数 Args: name: 名字 age: 年龄默认18 Returns: 问候语 return f你好, {name}年龄{age}岁 print(greet(Alice, 25)) print(greet(Bob)) # 使用默认值 # ---------- 可变参数 ---------- def sum_all(*args): *args接收任意数量位置参数元组 return sum(args) print(sum_all(1, 2, 3, 4, 5)) # 15 def print_info(**kwargs): **kwargs接收任意数量关键字参数字典 for key, value in kwargs.items(): print(f{key}: {value}) print_info(nameAlice, age30, cityBeijing) # ---------- 参数解包 ---------- def func(a, b, c): print(a, b, c) args (1, 2, 3) func(*args) # 解包列表/元组 kwargs {a: 10, b: 20, c: 30} func(**kwargs) # 解包字典 # ---------- 返回值 ---------- def get_stats(nums): return min(nums), max(nums), sum(nums)/len(nums) min_val, max_val, avg get_stats([1, 2, 3, 4, 5]) # ---------- 作用域 ---------- x 10 # 全局变量 def outer(): y 20 # 局部变量outer的 def inner(): nonlocal y # 引用外层函数变量 y 30 global x # 引用全局变量 x 100 inner() print(fy {y}) # 30 outer() print(fx {x}) # 100 # ---------- 闭包 ---------- def make_multiplier(factor): def multiplier(x): return x * factor return multiplier double make_multiplier(2) triple make_multiplier(3) print(double(10)) # 20 print(triple(10)) # 30 # ---------- 装饰器Decorator ---------- import functools import time def timer(func): 计时装饰器 functools.wraps(func) # 保留原函数信息 def wrapper(*args, **kwargs): start time.time() result func(*args, **kwargs) elapsed time.time() - start print(f{func.__name__} 执行耗时: {elapsed:.4f}秒) return result return wrapper timer def slow_function(): time.sleep(0.5) return 完成 print(slow_function()) # 自动计时 # ---------- Lambda函数 ---------- square lambda x: x ** 2 print(square(5)) # 25 # 常用场景排序 students [(Alice, 85), (Bob, 90), (Charlie, 78)] students.sort(keylambda x: x[1]) # 按分数排序 print(students) # [(Charlie, 78), (Alice, 85), (Bob, 90)]五、面向对象编程OOPpython# ---------- 类和对象 ---------- class Animal: 基类 # 类变量所有实例共享 species Animal # 构造函数 def __init__(self, name: str, age: int): self.name name # 实例变量 self.age age self.__private 私有 # 双下划线私有名称修饰 self._protected 保护 # 单下划线约定 # 实例方法 def speak(self): return f{self.name} 发出声音 # 类方法 classmethod def create_baby(cls, name): return cls(name, 0) # 静态方法 staticmethod def is_animal(): return True # 特殊方法魔术方法 def __str__(self): return f{self.name} ({self.age}岁) def __repr__(self): return fAnimal({self.name}, {self.age}) property def is_adult(self): 属性方法像访问属性一样调用 return self.age 18 # ---------- 继承 ---------- class Dog(Animal): 子类 def __init__(self, name, age, breed): super().__init__(name, age) # 调用父类构造 self.breed breed # 方法重写 def speak(self): return f{self.name} 汪汪叫 def fetch(self): return f{self.name} 接住了球 # 多重继承 class Flyable: def fly(self): return 飞行中 class Bird(Animal, Flyable): def speak(self): return f{self.name} 啾啾叫 # ---------- 使用 ---------- dog Dog(旺财, 3, 金毛) print(dog.speak()) # 旺财 汪汪叫 print(dog.is_adult) # True属性方法 print(dog.species) # Animal类变量 bird Bird(小小, 1) print(bird.fly()) # 飞行中 # ---------- 抽象基类 ---------- from abc import ABC, abstractmethod class Shape(ABC): abstractmethod def area(self): pass abstractmethod def perimeter(self): pass class Circle(Shape): def __init__(self, radius): self.radius radius def area(self): return 3.14159 * self.radius ** 2 def perimeter(self): return 2 * 3.14159 * self.radius # ---------- 数据类Python 3.7 ---------- from dataclasses import dataclass dataclass class Point: x: float y: float def distance_to_origin(self): return (self.x ** 2 self.y ** 2) ** 0.5 p Point(3, 4) print(p.distance_to_origin()) # 5.0六、异常处理python# ---------- try-except-finally ---------- def divide(a, b): try: result a / b except ZeroDivisionError as e: print(f错误: {e}) return None except TypeError as e: print(f类型错误: {e}) return None except Exception as e: print(f未知错误: {e}) return None else: # 没有异常时执行 print(计算成功) return result finally: # 无论是否异常都执行 print(清理资源) print(divide(10, 2)) # 5.0 print(divide(10, 0)) # None print(divide(10, a)) # None # ---------- 自定义异常 ---------- class NegativeNumberError(Exception): 自定义异常 def __init__(self, value, message不支持负数): self.value value self.message message super().__init__(self.message) def sqrt_positive(x): if x 0: raise NegativeNumberError(x) return x ** 0.5 try: sqrt_positive(-5) except NegativeNumberError as e: print(f捕获自定义异常: {e.value} {e.message}) # ---------- 断言Assert ---------- def process_age(age): assert age 0, 年龄不能为负数 assert age 150, 年龄超出合理范围 return age * 2 # 可通过 -O 参数禁用断言七、模块与包python# ---------- 导入方式 ---------- import math # 导入整个模块 import math as m # 别名导入 from math import sqrt, pi # 导入特定函数 from math import * # 导入所有不推荐 from mymodule import MyClass # 导入自定义 # ---------- 自定义模块mymodule.py ---------- # mymodule.py def my_function(): return Hello class MyClass: pass if __name__ __main__: # 只在直接运行时执行 print(模块独立运行) # ---------- 包结构 ---------- mypackage/ ├── __init__.py # 包标识可为空 ├── module1.py ├── module2.py └── subpackage/ ├── __init__.py └── module3.py # 使用 from mypackage import module1 from mypackage.subpackage import module3 # ---------- 常用模块 ---------- import os import sys import json import datetime import random import re from collections import Counter, defaultdict, deque from itertools import chain, cycle, product # ---------- 示例 ---------- # os: 操作系统接口 print(os.getcwd()) # 当前目录 print(os.listdir(.)) # 列出文件 # json: JSON处理 data {name: Alice, age: 30} json_str json.dumps(data) # 序列化 parsed json.loads(json_str) # 反序列化 # datetime: 日期时间 now datetime.datetime.now() print(now.strftime(%Y-%m-%d %H:%M:%S)) # random: 随机数 print(random.randint(1, 10)) # 1-10随机整数 print(random.choice([a, b, c])) # 随机选择 # re: 正则表达式 pattern re.compile(r\d) # 匹配数字 result pattern.findall(a1b2c3) print(result) # [1, 2, 3]八、迭代器与生成器python# ---------- 迭代器Iterator ---------- class Counter: def __init__(self, start, end): self.current start self.end end def __iter__(self): return self def __next__(self): if self.current self.end: raise StopIteration value self.current self.current 1 return value # 使用 counter Counter(0, 3) for num in counter: print(num) # 0, 1, 2 # ---------- 生成器Generator ---------- def fibonacci(limit): 生成器函数使用yield a, b 0, 1 count 0 while count limit: yield a a, b b, a b count 1 fib fibonacci(10) for num in fib: print(num, end ) # 0 1 1 2 3 5 8 13 21 34 # 生成器表达式 squares (x**2 for x in range(10)) print(next(squares)) # 0 print(next(squares)) # 1 # ---------- 生成器的send() ---------- def echo(): while True: received yield print(f接收到: {received}) e echo() next(e) # 启动生成器 e.send(Hello) # 发送值 e.send(World) # ---------- itertools工具 ---------- from itertools import count, cycle, repeat # 无限迭代器 for i in count(10): # 10, 11, 12, ... if i 15: break print(i) for item in cycle(ABC): # A, B, C, A, B, C, ... if item C: break print(item)九、函数式编程python# ---------- map ---------- numbers [1, 2, 3, 4, 5] squared list(map(lambda x: x**2, numbers)) print(squared) # [1, 4, 9, 16, 25] # ---------- filter ---------- evens list(filter(lambda x: x % 2 0, numbers)) print(evens) # [2, 4] # ---------- reduce ---------- from functools import reduce product reduce(lambda x, y: x * y, numbers) print(product) # 120 # ---------- sorted ---------- words [banana, apple, cherry] sorted_words sorted(words, keylen, reverseTrue) print(sorted_words) # [banana, cherry, apple] # ---------- partial偏函数 ---------- from functools import partial def power(base, exponent): return base ** exponent square partial(power, exponent2) cube partial(power, exponent3) print(square(5)) # 25 print(cube(5)) # 125 # ---------- lru_cache缓存装饰器 ---------- from functools import lru_cache lru_cache(maxsize100) def fib(n): if n 2: return n return fib(n-1) fib(n-2) print(fib(40)) # 快速计算因为缓存了中间结果 print(fib.cache_info()) # 查看缓存统计十、上下文管理器python# ---------- with语句 ---------- # 自动管理资源文件、锁、数据库连接等 # 文件操作 with open(test.txt, w) as f: f.write(Hello World) # 文件自动关闭 # ---------- 自定义上下文管理器 ---------- class ManagedResource: def __enter__(self): print(获取资源) return self def __exit__(self, exc_type, exc_val, exc_tb): print(释放资源) if exc_type: print(f发生异常: {exc_val}) return False # 不吞异常 with ManagedResource() as resource: print(使用资源) # raise ValueError(测试异常) # 会正常抛出 # 使用contextlib装饰器 from contextlib import contextmanager contextmanager def managed_resource(): print(获取资源) try: yield 资源对象 finally: print(释放资源) with managed_resource() as res: print(f使用{res})十一、并发编程python# ---------- threading多线程 ---------- import threading import time def worker(name, delay): print(f线程 {name} 开始) time.sleep(delay) print(f线程 {name} 结束) # 创建线程 threads [] for i in range(3): t threading.Thread(targetworker, args(fT{i}, i1)) threads.append(t) t.start() # 等待所有线程完成 for t in threads: t.join() # 使用线程锁 lock threading.Lock() shared_counter 0 def increment(): global shared_counter for _ in range(10000): with lock: # 自动获取和释放锁 shared_counter 1 # ---------- multiprocessing多进程 ---------- import multiprocessing def cpu_intensive_task(n): return sum(i**2 for i in range(n)) with multiprocessing.Pool(4) as pool: results pool.map(cpu_intensive_task, [10**6, 2*10**6, 3*10**6]) print(results) # ---------- asyncio异步IO ---------- import asyncio async def async_task(name, delay): print(f任务 {name} 开始) await asyncio.sleep(delay) print(f任务 {name} 完成) return f结果 {name} async def main(): # 并发执行多个异步任务 tasks [ async_task(A, 2), async_task(B, 1), async_task(C, 3) ] results await asyncio.gather(*tasks) print(results) # asyncio.run(main()) # 取消注释运行 # ---------- concurrent.futures ---------- from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor def square(n): return n * n with ThreadPoolExecutor(max_workers4) as executor: futures [executor.submit(square, i) for i in range(10)] results [f.result() for f in futures] print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]十二、常用标准库python# ---------- collections ---------- from collections import Counter, defaultdict, deque, OrderedDict, namedtuple # Counter计数器 text hello world counter Counter(text) print(counter.most_common(2)) # [(l, 3), (o, 2)] # defaultdict默认字典 d defaultdict(list) d[key].append(1) # 自动创建列表 print(d) # defaultdict(class list, {key: [1]}) # deque双端队列 dq deque([1, 2, 3]) dq.appendleft(0) dq.append(4) print(dq) # deque([0, 1, 2, 3, 4]) # namedtuple命名元组 Point namedtuple(Point, [x, y]) p Point(10, 20) print(p.x, p.y) # 10 20 # ---------- datetime ---------- from datetime import datetime, timedelta now datetime.now() future now timedelta(days7) print(future.strftime(%Y-%m-%d)) date_str 2024-01-01 date_obj datetime.strptime(date_str, %Y-%m-%d) # ---------- json ---------- import json data {name: Alice, scores: [95, 87, 92]} json_str json.dumps(data, indent2) parsed json.loads(json_str) # ---------- re ---------- import re pattern r\b[A-Za-z0-9._%-][A-Za-z0-9.-]\.[A-Z|a-z]{2,}\b text Contact: aliceexample.com match re.search(pattern, text) if match: print(match.group()) # aliceexample.com # ---------- os/pathlib ---------- from pathlib import Path p Path(.) print(p.absolute()) for file in p.glob(*.py): print(file.name) # ---------- random ---------- import random random.seed(42) print(random.random()) # [0,1)随机浮点 print(random.randint(1, 10)) # 随机整数 print(random.choice([a,b,c])) random.shuffle([a,b,c]) # 打乱 # ---------- sys ---------- import sys print(sys.argv) # 命令行参数 print(sys.platform) # 操作系统 sys.stdout.write(直接输出) # ---------- logging ---------- import logging logging.basicConfig(levellogging.INFO, format%(asctime)s - %(levelname)s - %(message)s) logging.info(信息日志) logging.warning(警告日志)十三、高级特性python# ---------- 装饰器带参数 ---------- 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(3) def say_hello(): return Hello print(say_hello()) # [Hello, Hello, Hello] # ---------- 类装饰器 ---------- class CountCalls: def __init__(self, func): self.func func self.count 0 def __call__(self, *args, **kwargs): self.count 1 print(f调用次数: {self.count}) return self.func(*args, **kwargs) CountCalls def test_func(): print(执行函数) test_func() test_func() # 计数增加 # ---------- 元类Metaclass ---------- class Meta(type): def __new__(cls, name, bases, dct): dct[version] 1.0 return super().__new__(cls, name, bases, dct) class MyClass(metaclassMeta): pass print(MyClass.version) # 1.0 # ---------- 描述符Descriptor ---------- class PositiveNumber: def __set_name__(self, owner, name): self.name name def __get__(self, obj, objtypeNone): return obj.__dict__.get(self.name) def __set__(self, obj, value): if value 0: raise ValueError(f{self.name} 必须为正数) obj.__dict__[self.name] value class Person: age PositiveNumber() def __init__(self, age): self.age age p Person(25) print(p.age) # 25 # p.age -5 # ValueError # ---------- 属性动态化 ---------- class Dynamic: def __getattr__(self, name): return f未知属性: {name} def __setattr__(self, name, value): print(f设置 {name} {value}) super().__setattr__(name, value) def __call__(self, *args): print(f调用参数: {args}) d Dynamic() print(d.xyz) # 未知属性: xyz d.name test # 设置 name test d(1, 2, 3) # 调用参数: (1, 2, 3) # ---------- 类型提示Type Hints ---------- from typing import List, Dict, Optional, Union, Any, Callable def process_list(items: List[int]) - Dict[str, int]: return {sum: sum(items), count: len(items)} def find_user(user_id: int) - Optional[Dict[str, Any]]: # 可能返回None return {id: user_id, name: Alice} # 联合类型 def parse(data: Union[str, bytes]) - str: if isinstance(data, bytes): return data.decode() return data # 可调用 def execute(func: Callable[[int, int], int], a: int, b: int) - int: return func(a, b)十四、文件与IOpython# ---------- 文本文件读写 ---------- # 读文件 with open(example.txt, r, encodingutf-8) as f: content f.read() # 全部读取 line f.readline() # 读一行 lines f.readlines() # 读所有行列表 # 写文件 with open(output.txt, w, encodingutf-8) as f: f.write(Hello\n) f.write(World\n) f.writelines([Line1\n, Line2\n]) # 追加模式 with open(output.txt, a) as f: f.write(追加内容\n) # ---------- 二进制文件 ---------- with open(data.bin, wb) as f: f.write(b\x00\x01\x02\x03) with open(data.bin, rb) as f: data f.read() print(data.hex()) # 00010203 # ---------- 内存IOStringIO, BytesIO ---------- from io import StringIO, BytesIO sio StringIO() sio.write(Hello World) sio.seek(0) print(sio.read()) # Hello World bio BytesIO() bio.write(b\x00\x01\x02) bio.seek(0) print(bio.read().hex()) # ---------- 文件操作os, shutil ---------- import os import shutil os.mkdir(new_folder) # 创建目录 os.rename(old.txt, new.txt) # 重命名 os.remove(file.txt) # 删除文件 shutil.copy(src.txt, dst.txt) # 复制文件 shutil.rmtree(folder) # 删除目录树十五、常用第三方库简介python# ---------- NumPy数值计算 ---------- # import numpy as np # arr np.array([1, 2, 3, 4]) # print(arr.mean()) # 2.5 # ---------- Pandas数据分析 ---------- # import pandas as pd # df pd.DataFrame({Name: [Alice, Bob], Age: [25, 30]}) # print(df.describe()) # ---------- Matplotlib绘图 ---------- # import matplotlib.pyplot as plt # plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) # plt.show() # ---------- RequestsHTTP请求 ---------- # import requests # response requests.get(https://api.github.com) # print(response.status_code) # ---------- SQLAlchemyORM ---------- # from sqlalchemy import create_engine # engine create_engine(sqlite:///test.db) # ---------- Django/FlaskWeb框架 ---------- # from flask import Flask # app Flask(__name__) # ---------- pytest测试框架 ---------- # def test_addition(): # assert 1 1 2十六、代码风格与最佳实践python# ---------- PEP 8 规范 ---------- # 1. 缩进4个空格 # 2. 行宽79字符 # 3. 命名规范 # - 类名驼峰CamelCase # - 函数/变量小写加下划线snake_case # - 常量全大写加下划线UPPER_CASE # 4. 空行函数间空两行类方法间空一行 # ---------- 类型检查mypy ---------- # 使用类型注解运行 mypy 进行静态检查 # ---------- 格式化工具 ---------- # black: 自动格式化代码 # isort: 自动排序导入 # flake8: 代码检查 # ---------- 文档字符串 ---------- def complex_function(param1: int, param2: str) - bool: 函数功能说明 Args: param1: 第一个参数说明 param2: 第二个参数说明 Returns: 返回值说明 Raises: ValueError: 异常情况说明 Examples: complex_function(1, test) True return True # ---------- 性能优化技巧 ---------- # 1. 使用生成器而非列表节省内存 large_range range(1000000) # 不占用大量内存 # 2. 使用join拼接字符串 parts [a, b, c] result .join(parts) # 比 快 # 3. 使用局部变量减少查找开销 import math local_sqrt math.sqrt # 缓存函数引用 # 4. 使用__slots__节省内存 class SmallClass: __slots__ [x, y] # 限制属性节省内存 def __init__(self, x, y): self.x x self.y y