几个让Python代码更优雅的技巧
Python以简洁著称,但有些特性还是容易被忽略。今天分享几个提升代码质量的实用技巧。
1. 路径管理用Pathlib
别再到处用os.path了,pathlib更现代:
from pathlib import Path
# 自动处理不同系统的路径分隔符
data_dir = Path("data") / "raw" / "2023.csv"
if data_dir.exists():
with data_dir.open() as f:
print(f.read())
2. 数据类省去样板代码
普通类需要写一堆初始化代码:
# 旧方式
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 新方式
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
自动生成init、repr等方法,整洁多了。
3. 枚举让常量更规范
用普通变量定义常量容易出错:
# 不推荐
STATUS_DRAFT = 1
STATUS_PUBLISHED = 2
# 推荐
from enum import Enum
class Status(Enum):
DRAFT = 1
PUBLISHED = 2
类型提示友好,遍历也方便。
4. 函数参数解包
当列表元素正好对应函数参数时:
def draw_point(x, y, color):
print(f"在({x}, {y})画{color}点")
point = [10, 20, "红色"]
draw_point(*point) # 列表解包
config = {
"x": 30, "y": 40, "color": "蓝色"}
draw_point(**config) # 字典解包
5. 上下文管理器处理资源
用with语句自动管理资源:
# 文件自动关闭
with open("log.txt", "r") as f:
content = f.read()
# 自定义上下文管理器
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
print(f"耗时: {time.time() - start:.2f}秒")
with timer():
# 执行耗时操作
sum(range(1000000))
6. zip并行迭代多个列表
names = ["小明", "小红", "小刚"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}分")
处理完最短的那个自动停止,不用担心索引越界。
总结
这些小技巧能让代码更Pythonic,也更易维护。建议在项目中逐步尝试,感受它们带来的变化。你最喜欢哪个?欢迎留言讨论。