Python 函数避坑指南:从“能跑就行”到“干净专业”
·
Python 函数避坑指南:从“能跑就行”到“干净专业”
Python 以简洁优雅著称,但“能跑就行”的函数写法,往往埋下隐患。随着项目变大,这些小问题会演变成难以维护的噩梦。本文总结 7 个常见错误 及其 专业级替代方案,助你写出高效、可读、可维护的 Python 函数!
1. ❌ 别用可变对象作默认参数
✅ 正确做法:用 None 初始化
错误示例:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item('apple')) # ['apple']
print(add_item('banana')) # ['apple', 'banana'] ???
多次调用会共享同一个列表!
正确写法:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item('apple')) # ['apple']
print(add_item('banana')) # ['banana']
原理:默认参数在函数定义时只计算一次,不是每次调用!
2. ❌ 别返回不一致的数据类型
✅ 统一返回类型,或使用 Optional
错误示例:
def process(value):
if value > 10:
return "Success"
else:
return 0 # Mixing str and int
推荐写法:
from typing import Optional
def process(value: int) -> Optional[str]:
return "Success" if value > 10 else None
类型一致 = 更少 bug + 更好调试!
3. ❌ 别写“全能型”臃肿函数
✅ 单一职责原则:小而专一
错误示例:
def calculate_price(quantity, price, tax_rate, discount, shipping):
total = (quantity * price) + shipping
total += total * tax_rate
if discount:
total -= total * discount
return total
重构后:
def calculate_subtotal(quantity, price):
return quantity * price
def apply_tax(subtotal, tax_rate):
return subtotal + (subtotal * tax_rate)
def apply_discount(amount, discount):
return amount - (amount * discount)
def calculate_total(quantity, price, tax_rate, discount, shipping):
subtotal = calculate_subtotal(quantity, price)
taxed_total = apply_tax(subtotal, tax_rate)
discounted_total = apply_discount(taxed_total, discount)
return discounted_total + shipping
小函数 = 易测试 + 易复用 + 易理解!
4. ❌ 别用 % 或 .format() 格式化字符串
✅ 用 f-strings(Python 3.6+)
过时写法:
def greet(name, age):
return "Hello, my name is %s and I am %d years old." % (name, age)
或者:
def greet(name, age):
return "Hello, my name is {} and I am {} years old.".format(name, age)
现代写法:
def greet(name, age):
return f"Hello, my name is {name} and I am {age} years old."
f-strings 更快、更简洁、支持表达式!
5. ❌ 别让函数“类型模糊”
✅ 使用 Type Hints 提升可读性
模糊函数:
def add_numbers(a, b):
return a + b
清晰函数:
def add_numbers(a: int, b: int) -> int:
return a + b
类型提示 = 自文档化代码 + IDE 更智能 + 减少类型错误!
6. ❌ 别手动维护循环索引
✅ 用 enumerate() 更 Pythonic
笨重写法:
fruits = ["Mango", "Pineapple", "Guava"]
index = 0
for fruit in fruits:
print(f"{index}: {fruit}")
index += 1
优雅写法:
fruits = ["Mango", "Pineapple", "Guava"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
简洁、安全、符合 Python 哲学!
7. ❌ 别用 try-except 做常规流程控制
✅ 优先使用内置安全方法
过度异常处理:
def get_price(data):
try:
return data["price"]
except KeyError:
return 0
更优解:
def get_price(data):
return data.get("price", 0)
异常应处理“异常情况”,而非正常逻辑分支!
🎯 总结:写出专业级 Python 函数的 3 大原则
- 可预测性:输入输出类型明确,行为一致。
- 单一职责:一个函数只做一件事,并做到极致。
- Pythonic 风格:善用语言特性(如 f-strings、
enumerate、.get()),拒绝冗余。
💡 行动建议:花 10 分钟回顾你的旧函数——用这 7 条准则重构它们。你会发现:代码不仅更干净,连 bug 都变少了!
现在就升级你的 Python 函数写法吧!
简洁 ≠ 简陋,聪明 ≠ 复杂。真正的高手,写的是别人一眼就能懂的代码。
更多推荐


所有评论(0)