Python 知识速查表
本页面汇总了 Python 编程中最常用的语法和知识点,方便快速查阅。
数据类型
| 类型 | 示例 | 说明 |
|---|---|---|
int | 10, -5, 0 | 整数,无精度限制 |
float | 3.14, -2.5 | 浮点数,双精度 |
str | "hello", 'world' | 字符串,不可变 |
bool | True, False | 布尔值,是 int 的子类 |
list | [1, 2, 3] | 列表,可变有序序列 |
tuple | (1, 2, 3) | 元组,不可变有序序列 |
dict | {"a": 1} | 字典,键值对映射 |
set | {1, 2, 3} | 集合,无序不重复元素 |
类型判断与转换
# 类型检查
type(123) # <class 'int'>
isinstance(123, int) # True - 推荐使用,支持继承判断
isinstance(123, (int, float)) # True - 支持多类型检查
# 类型转换
int("123") # 字符串转整数
int(3.9) # 浮点数转整数(截断)-> 3
float("3.14") # 字符串转浮点数
str(123) # 整数转字符串
list("abc") # 字符串转列表 -> ['a', 'b', 'c']
tuple([1, 2]) # 列表转元组 -> (1, 2)
set([1, 1, 2]) # 列表转集合(去重)-> {1, 2}
bool(0) # 转布尔值 -> False
bool("") # 空字符串 -> False
bool([]) # 空列表 -> False
假值判断
以下值在布尔上下文中为 False:
False # 布尔假值
None # 空值
0 # 数字零
0.0 # 浮点零
"" # 空字符串
() # 空元组
[] # 空列表
{} # 空字典
set() # 空集合
字符串格式化
f-string(推荐,Python 3.6+)
name = "张三"
age = 25
# 基础用法
f"姓名:{name},年龄:{age}"
# 表达式计算
f"明年 {age + 1} 岁"
# 调用方法
f"姓名:{name.upper()}"
# 格式化数字
pi = 3.14159
f"{pi:.2f}" # 保留两位小数 -> "3.14"
f"{pi:>8.2f}" # 右对齐,宽度8 -> " 3.14"
f"{pi:<8.2f}" # 左对齐 -> "3.14 "
f"{pi:^8.2f}" # 居中对齐 -> " 3.14 "
f"{pi:08.2f}" # 用0填充 -> "00003.14"
# 格式化整数
num = 42
f"{num:05d}" # 宽度5,前导0 -> "00042"
f"{num:>5d}" # 右对齐 -> " 42"
# 千位分隔符
big_num = 1234567
f"{big_num:,}" # -> "1,234,567"
f"{big_num:_}" # 下划线分隔 -> "1_234_567"
# 百分比
ratio = 0.856
f"{ratio:.2%}" # -> "85.60%"
# 进制转换
n = 255
f"{n:b}" # 二进制 -> "11111111"
f"{n:o}" # 八进制 -> "377"
f"{n:x}" # 十六进制(小写)-> "ff"
f"{n:X}" # 十六进制(大写)-> "FF"
# 科学计数法
f"{12345.6789:e}" # -> "1.234568e+04"
f"{12345.6789:.2e}" # -> "1.23e+04"
# 日期格式化
from datetime import datetime
now = datetime.now()
f"{now:%Y-%m-%d %H:%M:%S}" # -> "2024-01-15 14:30:00"
# 嵌套引号
f"他说:'{name}'"
# 转义大括号
f"{{这是一个大括号}}" # -> "{这是一个大括号}"
format() 方法
# 位置参数
"{} {}".format("Hello", "World") # "Hello World"
"{0} {1} {0}".format("A", "B") # "A B A"
# 关键字参数
"{name} is {age}".format(name="张三", age=25)
# 格式化
"{:.2f}".format(3.14159) # "3.14"
"{:>10}".format("hello") # " hello"
"{:05d}".format(42) # "00042"
% 格式化(旧式,不推荐)
"%s is %d years old" % ("张三", 25) # "张三 is 25 years old"
"%.2f" % 3.14159 # "3.14"
运算符
算术运算符
+ # 加法
- # 减法
* # 乘法
/ # 除法(结果为浮点数)
// # 整除(向下取整)
% # 取余
** # 幂运算
# 注意整除的行为
7 // 2 # 3
-7 // 2 # -4(向下取整,不是截断)
比较运算符
== # 等于(值比较)
!= # 不等于
> # 大于
< # 小于
>= # 大于等于
<= # 小于等于
is # 身份比较(是否同一对象)
is not # 不是同一对象
# 链式比较
x = 5
1 < x < 10 # True,等价于 1 < x and x < 10
逻辑运算符
and # 逻辑与(短路求值)
or # 逻辑或(短路求值)
not # 逻辑非
# 短路求值示例
a = 0
b = a or "default" # b = "default"(a为假,返回第二个值)
c = "hello" or "default" # c = "hello"(第一个为真,直接返回)
d = "hello" and "world" # d = "world"
e = "" and "world" # e = ""(第一个为假,直接返回)
成员运算符
in # 成员是否在序列中
not in # 成员不在序列中
'a' in 'abc' # True
1 in [1, 2, 3] # True
'x' in {'x': 1} # True(检查键)
字符串操作
s = "Hello World"
# 切片
s[0] # 'H' - 第一个字符
s[-1] # 'd' - 最后一个字符
s[0:5] # 'Hello' - 切片 [start:end)
s[:5] # 'Hello' - 从开头到索引5
s[6:] # 'World' - 从索引6到结尾
s[::2] # 'HloWrd' - 步长为2
s[::-1] # 'dlroW olleH' - 反转字符串
# 常用方法
s.upper() # 'HELLO WORLD' - 转大写
s.lower() # 'hello world' - 转小写
s.title() # 'Hello World' - 每个单词首字母大写
s.capitalize() # 'Hello world' - 首字母大写
s.strip() # 去除两端空白
s.lstrip() # 去除左侧空白
s.rstrip() # 去除右侧空白
s.replace('o', 'X') # 'HellX WXrld' - 替换
s.split() # ['Hello', 'World'] - 按空白分割
s.split('l') # ['He', '', 'o Wor', 'd'] - 按字符分割
'-'.join(['a', 'b']) # 'a-b' - 用指定字符连接
s.startswith('Hello') # True - 检查开头
s.endswith('World') # True - 检查结尾
s.find('World') # 6 - 查找子串位置,未找到返回 -1
s.index('World') # 6 - 查找子串位置,未找到抛出异常
s.count('l') # 3 - 统计出现次数
s.isalpha() # False - 是否全为字母
s.isdigit() # False - 是否全为数字
s.isalnum() # True - 是否全为字母或数字
s.center(20, '-') # '----Hello World-----' - 居中填充
# 多行字符串
multi = """第一行
第二行
第三行"""
列表操作
lst = [1, 2, 3, 4, 5]
# 访问和切片
lst[0] # 1 - 第一个元素
lst[-1] # 5 - 最后一个元素
lst[1:3] # [2, 3] - 切片
lst[::2] # [1, 3, 5] - 步长为2
lst[::-1] # [5, 4, 3, 2, 1] - 反转
# 添加元素
lst.append(6) # 末尾添加 -> [1, 2, 3, 4, 5, 6]
lst.insert(0, 0) # 指定位置插入 -> [0, 1, 2, 3, 4, 5, 6]
lst.extend([7, 8]) # 扩展列表 -> [0, 1, 2, 3, 4, 5, 6, 7, 8]
# 删除元素
lst.remove(0) # 删除第一个匹配的元素
lst.pop() # 删除并返回最后一个元素
lst.pop(0) # 删除并返回指定索引的元素
del lst[0] # 删除指定索引的元素
lst.clear() # 清空列表
# 查找和统计
lst.index(3) # 返回元素索引,未找到抛出异常
lst.count(2) # 统计元素出现次数
3 in lst # True - 检查元素是否存在
# 排序和反转
lst.sort() # 原地排序(升序)
lst.sort(reverse=True) # 原地排序(降序)
lst.sort(key=lambda x: -x) # 自定义排序
sorted(lst) # 返回新排序列表
lst.reverse() # 原地反转
reversed(lst) # 返回反转迭代器
# 复制
lst.copy() # 浅复制
lst[:] # 浅复制
list(lst) # 浅复制
# 其他
len(lst) # 列表长度
max(lst) # 最大值
min(lst) # 最小值
sum(lst) # 求和
字典操作
d = {"name": "张三", "age": 25}
# 访问
d["name"] # '张三' - 键不存在会报错
d.get("name") # '张三' - 推荐使用
d.get("gender", "未知") # '未知' - 提供默认值
# 修改
d["age"] = 26 # 修改值
d["city"] = "北京" # 添加新键值对
d.update({"gender": "男", "job": "工程师"}) # 批量更新
d.setdefault("country", "中国") # 键不存在则添加,存在则不变
# 删除
del d["city"] # 删除键值对
d.pop("age") # 删除并返回值
d.pop("age", None) # 键不存在返回默认值
d.popitem() # 删除并返回最后一个键值对(Python 3.7+)
d.clear() # 清空字典
# 遍历
for key in d: # 遍历键
print(key)
for key in d.keys(): # 遍历键
print(key)
for value in d.values(): # 遍历值
print(value)
for key, value in d.items(): # 遍历键值对
print(key, value)
# 检查
"name" in d # True - 检查键是否存在
"gender" not in d # True
# 其他
len(d) # 键值对数量
d.copy() # 浅复制
dict.fromkeys(['a', 'b'], 0) # 创建字典 {'a': 0, 'b': 0}
# 合并字典(Python 3.9+)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
d3 = d1 | d2 # {"a": 1, "b": 3, "c": 4}
d1 |= d2 # 原地合并
集合操作
s = {1, 2, 3}
# 添加和删除
s.add(4) # 添加元素
s.remove(3) # 删除元素,不存在会报错
s.discard(3) # 删除元素,不存在不报错
s.pop() # 随机删除并返回一个元素
s.clear() # 清空集合
# 集合运算
a = {1, 2, 3}
b = {2, 3, 4}
a | b # 并集 -> {1, 2, 3, 4}
a & b # 交集 -> {2, 3}
a - b # 差集 -> {1}
a ^ b # 对称差集 -> {1, 4}
# 集合判断
a.issubset(b) # a 是否是 b 的子集
a.issuperset(b) # a 是否是 b 的超集
a.isdisjoint(b) # a 和 b 是否无交集
# 去重应用
list(set([1, 1, 2, 2, 3])) # [1, 2, 3] - 列表去重
推导式
列表推导式
# 基础语法:[表达式 for 变量 in 可迭代对象 if 条件]
# 生成平方数
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件过滤
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# 带条件表达式
result = ["偶数" if x % 2 == 0 else "奇数" for x in range(5)]
# ['偶数', '奇数', '偶数', '奇数', '偶数']
# 嵌套循环
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# 展平嵌套列表
flat = [x for row in matrix for x in row]
# [0, 0, 0, 0, 1, 2, 0, 2, 4]
字典推导式
# 基础语法:{键表达式: 值表达式 for 变量 in 可迭代对象 if 条件}
# 列表转字典
items = ['a', 'b', 'c']
d = {k: v for v, k in enumerate(items)}
# {'a': 0, 'b': 1, 'c': 2}
# 过滤字典
scores = {'a': 90, 'b': 60, 'c': 85}
passed = {k: v for k, v in scores.items() if v >= 80}
# {'a': 90, 'c': 85}
# 键值互换
original = {'a': 1, 'b': 2}
swapped = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b'}
集合推导式
# 语法:{表达式 for 变量 in 可迭代对象 if 条件}
# 生成不重复的平方数
squares = {x**2 for x in [1, -1, 2, -2]}
# {1, 4}
生成器表达式
# 使用圆括号,惰性求值,节省内存
gen = (x**2 for x in range(10))
# 常用于求和、最大值等
total = sum(x**2 for x in range(100)) # 不需要额外的方括号
函数
# 基础函数
def greet(name, greeting="你好"):
"""函数文档字符串"""
return f"{greeting},{name}!"
# 调用方式
greet("张三") # "你好,张三!"
greet("张三", "早上好") # "早上好,张三!"
greet(greeting="哈喽", name="李四") # "哈喽,李四!"
# *args 接收任意数量的位置参数
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3, 4) # 10
# **kwargs 接收任意数量的关键字参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="张三", age=25)
# 位置限定参数(/ 后面只能是关键字参数)
def func(a, b, /, c, d, *, e, f):
pass
func(1, 2, c=3, d=4, e=5, f=6) # a, b 只能位置传参,e, f 只能关键字传参
# 返回多个值(实际返回元组)
def get_point():
return 10, 20
x, y = get_point()
# Lambda 函数
square = lambda x: x ** 2
add = lambda a, b: a + b
sorted([3, 1, 2], key=lambda x: -x) # 降序排序
# 函数注解
def add(a: int, b: int) -> int:
return a + b
# 闭包和装饰器
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
c() # 1
c() # 2
文件操作
# 读取文件(推荐使用 with 语句)
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部内容
lines = f.readlines() # 读取所有行,返回列表
line = f.readline() # 读取一行
# 逐行读取(内存高效)
with open("file.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 写入文件
with open("file.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.writelines(["第二行\n", "第三行\n"])
# 追加写入
with open("file.txt", "a", encoding="utf-8") as f:
f.write("追加内容\n")
# 读写模式
# 'r' - 只读(默认)
# 'w' - 写入(覆盖)
# 'a' - 追加
# 'r+' - 读写
# 'w+' - 写读(覆盖)
# 'a+' - 追加读写
# 'b' - 二进制模式,如 'rb', 'wb'
# JSON 文件
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f) # 读取 JSON
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2) # 写入 JSON
json_str = json.dumps(data) # 对象转 JSON 字符串
obj = json.loads(json_str) # JSON 字符串转对象
异常处理
# 基础异常处理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除零错误: {e}")
except (TypeError, ValueError) as e:
print(f"类型或值错误: {e}")
except Exception as e:
print(f"其他错误: {e}")
else:
print("没有异常时执行")
finally:
print("无论是否异常都执行")
# 抛出异常
raise ValueError("无效的值")
# 自定义异常
class MyError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
raise MyError("自定义错误信息")
# 上下文管理器
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
return False # 返回 True 会抑制异常
with FileManager("test.txt") as f:
content = f.read()
类与面向对象
class Person:
# 类属性
species = "人类"
# 初始化方法
def __init__(self, name, age):
# 实例属性
self.name = name
self._age = age # 约定私有属性
self.__id = 12345 # 名称改写私有属性
# 实例方法
def introduce(self):
return f"我是{self.name},今年{self._age}岁"
# 类方法
@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, 2024 - birth_year)
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 属性装饰器
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value >= 0:
self._age = value
else:
raise ValueError("年龄不能为负")
# 字符串表示
def __str__(self):
return f"Person({self.name})"
def __repr__(self):
return f"Person(name='{self.name}', age={self._age})"
# 继承
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def introduce(self):
return f"{super().introduce()},{self.grade}年级"
# 使用
p = Person("张三", 25)
print(p.introduce())
print(Person.is_adult(20)) # True
数据类(dataclass)
from dataclasses import dataclass, field, asdict, astuple
@dataclass
class Person:
name: str
age: int
city: str = "未知"
tags: list = field(default_factory=list)
p = Person("张三", 25)
print(p) # Person(name='张三', age=25, city='未知', tags=[])
print(asdict(p)) # {'name': '张三', 'age': 25, 'city': '未知', 'tags': []}
# 常用参数
@dataclass(frozen=True) # 不可变
@dataclass(order=True) # 支持排序
@dataclass(slots=True) # 内存优化
class Point:
x: float
y: float
描述符
# 描述符:实现 __get__、__set__、__delete__ 的类
class Typed:
def __init__(self, name, expected_type):
self.name = name
self.expected_type = expected_type
def __get__(self, obj, owner):
return obj.__dict__.get(self.name)
def __set__(self, obj, value):
if not isinstance(value, self.expected_type):
raise TypeError(f"{self.name} 应为 {self.expected_type}")
obj.__dict__[self.name] = value
class Person:
name = Typed("name", str)
age = Typed("age", int)
slots 内存优化
class Point:
__slots__ = ['x', 'y'] # 限制属性,节省内存
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
# p.z = 3 # AttributeError
元类
# 元类:创建类的类
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
pass
db1 = Database()
db2 = Database()
print(db1 is db2) # True
异步编程
import asyncio
# 定义协程
async def fetch_data(url):
print(f"开始获取 {url}")
await asyncio.sleep(1) # 模拟 I/O 操作
return f"{url} 的数据"
# 运行协程
async def main():
# 顺序执行
result1 = await fetch_data("url1")
result2 = await fetch_data("url2")
# 并发执行
results = await asyncio.gather(
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3")
)
return results
# 运行
asyncio.run(main())
# 创建任务
async def with_tasks():
task1 = asyncio.create_task(fetch_data("url1"))
task2 = asyncio.create_task(fetch_data("url2"))
result1 = await task1
result2 = await task2
return result1, result2
# 超时控制
async def with_timeout():
try:
result = await asyncio.wait_for(
fetch_data("url"),
timeout=2.0
)
except asyncio.TimeoutError:
print("请求超时")
# 异步上下文管理器
class AsyncResource:
async def __aenter__(self):
print("获取资源")
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
print("释放资源")
async def use_resource():
async with AsyncResource() as r:
print("使用资源")
# 异步迭代器
class AsyncCounter:
def __init__(self, limit):
self.limit = limit
def __aiter__(self):
self.count = 0
return self
async def __anext__(self):
if self.count < self.limit:
await asyncio.sleep(0.1)
self.count += 1
return self.count
raise StopAsyncIteration
async def count_async():
async for num in AsyncCounter(3):
print(num)
常用标准库速查
| 模块 | 用途 | 常用函数/类 |
|---|---|---|
os | 操作系统接口 | os.getcwd(), os.listdir(), os.path.join() |
sys | 系统参数 | sys.argv, sys.path, sys.exit() |
json | JSON 处理 | json.load(), json.dump(), json.dumps() |
datetime | 日期时间 | datetime.now(), datetime.strptime(), timedelta |
re | 正则表达式 | re.search(), re.findall(), re.sub() |
math | 数学函数 | math.sqrt(), math.ceil(), math.floor() |
random | 随机数 | random.random(), random.randint(), random.choice() |
collections | 容器扩展 | Counter, defaultdict, deque, namedtuple |
itertools | 迭代工具 | chain(), cycle(), islice(), combinations() |
functools | 函数工具 | partial(), lru_cache(), wraps |
pathlib | 路径操作 | Path(), Path.exists(), Path.read_text() |
typing | 类型注解 | List, Dict, Optional, Union, TypeVar |
asyncio | 异步编程 | asyncio.run(), asyncio.gather(), create_task() |
logging | 日志记录 | logging.info(), logging.error(), basicConfig() |
argparse | 命令行参数 | ArgumentParser, add_argument(), parse_args() |
subprocess | 子进程 | subprocess.run(), subprocess.Popen() |
threading | 多线程 | Thread(), Lock(), Event() |
multiprocessing | 多进程 | Process(), Pool(), Queue() |
contextlib | 上下文工具 | contextmanager, closing() |
dataclasses | 数据类 | @dataclass, field() |
enum | 枚举 | Enum, IntEnum, auto() |
copy | 复制 | copy(), deepcopy() |
hashlib | 哈希 | md5(), sha256(), hexdigest() |
pickle | 序列化 | pickle.dump(), pickle.load() |
常见错误速查
常见异常类型
| 异常 | 说明 | 常见原因 |
|---|---|---|
NameError | 名称未定义 | 变量名拼写错误、未声明就使用 |
TypeError | 类型错误 | 类型不匹配、参数数量不对 |
ValueError | 值错误 | 类型正确但值不合法,如 int("abc") |
IndexError | 索引越界 | 列表/字符串索引超出范围 |
KeyError | 键不存在 | 字典访问不存在的键 |
AttributeError | 属性不存在 | 对象没有该属性或方法 |
ZeroDivisionError | 除零错误 | 除数为 0 |
FileNotFoundError | 文件未找到 | 文件路径错误 |
IndentationError | 缩进错误 | 缩进不一致 |
SyntaxError | 语法错误 | 代码语法不正确 |
常见陷阱
# 1. 可变默认参数
def add_item(item, lst=[]): # 错误!默认值会被共享
lst.append(item)
return lst
# 正确做法
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
# 2. 循环中的闭包
funcs = [lambda: i for i in range(3)]
for f in funcs:
print(f()) # 输出 2, 2, 2
# 正确做法
funcs = [lambda i=i: i for i in range(3)]
for f in funcs:
print(f()) # 输出 0, 1, 2
# 3. 列表乘法陷阱
matrix = [[0] * 3] * 3
matrix[0][0] = 1 # 所有行的第一个元素都变了!
# 正确做法
matrix = [[0] * 3 for _ in range(3)]
# 4. 字典迭代时修改
d = {'a': 1, 'b': 2}
for k in d:
if k == 'a':
del d[k] # RuntimeError
# 正确做法
for k in list(d.keys()):
if k == 'a':
del d[k]
# 5. 整数缓存
a = 256
b = 256
a is b # True(小整数被缓存)
a = 257
b = 257
a is b # 可能 False(大整数不被缓存)
# 应该用 == 比较值
a == b # True
# 6. 浮点数精度
0.1 + 0.2 == 0.3 # False
# 使用 decimal 或 math.isclose
from decimal import Decimal
Decimal('0.1') + Decimal('0.2') == Decimal('0.3') # True
性能优化技巧
1. 使用内置函数和推导式
# 慢
result = []
for i in range(1000):
result.append(i * 2)
# 快
result = [i * 2 for i in range(1000)]
# 更快(对于内置操作)
result = list(map(lambda x: x * 2, range(1000)))
2. 字符串连接
# 慢
result = ""
for s in strings:
result += s
# 快
result = "".join(strings)
3. 成员检查
# 慢(列表 O(n))
if item in my_list:
pass
# 快(集合 O(1))
my_set = set(my_list)
if item in my_set:
pass
4. 使用局部变量
# 慢
import math
def compute():
for i in range(10000):
math.sqrt(i) # 每次都要查找 math.sqrt
# 快
from math import sqrt
def compute():
for i in range(10000):
sqrt(i)
# 或者
def compute():
sqrt = math.sqrt
for i in range(10000):
sqrt(i)
5. 使用生成器节省内存
# 占用大量内存
result = [process(item) for item in large_list]
# 内存友好
result = (process(item) for item in large_list)
6. 缓存结果
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
7. 使用 __slots__ 减少内存
# 普通类
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# 优化后
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
8. 避免不必要的抽象
# 慢(多层函数调用)
def process_data(data):
return transform(validate(parse(data)))
# 快(直接操作)
def process_data(data):
parsed = data.strip().split(',')
if not parsed:
return None
return [float(x) for x in parsed]
代码风格速查(PEP 8)
# 命名规范
module_name.py # 模块:小写下划线
ClassName # 类:大驼峰
function_name # 函数:小写下划线
CONSTANT_NAME # 常量:大写下划线
_private_var # 私有:单下划线前缀
__private_var # 名称改写:双下划线前缀
# 缩进
# 使用 4 个空格,不用 Tab
# 行长度
# 最大 79 字符,注释/文档字符串最大 72 字符
# 空行
# 类之间 2 个空行
# 方法之间 1 个空行
# 导入顺序
import os # 标准库
import sys
from collections import Counter
import numpy as np # 第三方库
import pandas as pd
from mymodule import func # 本地模块
# 空格
# 运算符两边各一个空格
x = 1 + 2
# 逗号后面一个空格
func(1, 2, 3)
# 冒号后面一个空格(字典、切片)
d = {"key": "value"}
lst[1:3]
类型注解速查
from typing import List, Dict, Set, Tuple, Optional, Union, Any, Callable
# 基础类型
name: str = "张三"
age: int = 25
score: float = 95.5
# 容器类型
names: List[str] = ["张三", "李四"]
scores: Dict[str, int] = {"张三": 90, "李四": 85}
unique: Set[int] = {1, 2, 3}
point: Tuple[int, int] = (10, 20)
# 可选类型
middle_name: Optional[str] = None # str 或 None
# 联合类型
id: Union[int, str] = 123 # int 或 str
# 任意类型
data: Any = "anything"
# 函数类型
def greet(name: str) -> str:
return f"Hello, {name}"
# 回调类型
callback: Callable[[int, int], int] = lambda a, b: a + b
# 泛型(Python 3.12+)
def first_item[T](items: list[T]) -> T:
return items[0]
# 类型别名
Vector = List[float]
Matrix = List[Vector]