
场景:需要将1-100中的偶数平方存入列表
菜鸟写法:
result = []
for i in range(1,101):
if i%2 ==0:
result.append(i**2)老手套路:
squares = [x**2 for x in range(1,101) if x%2==0]原理:
进阶用法:字典/集合推导式,文件批量处理
场景:计算BMI指数(需处理公斤/磅单位)
菜鸟写法:
def calc_bmi(weight, height, unit='kg'):
if unit == 'kg':
return weight/(height**2)
elif unit == 'lb':
return (weight*0.453592)/(height*0.0254)**2
else:
return None老手套路:
def calc_bmi(weight, height, unit='kg', *, factor=1):
return (weight * factor) / (height **2)
# 调用示例
calc_bmi(70, 1.75) # 默认公斤
calc_bmi(150, 64, unit='lb', factor=0.453592/(0.0254**2))原理:
扩展技巧:可变参数*args和**kwargs的妙用
场景:安全处理文件读写
菜鸟写法:
f = open('data.txt', 'r')
try:
content = f.read()
finally:
f.close()老手套路:
with open('data.txt', 'r') as f:
content = f.read()
# 自动处理关闭和资源释放原理:
实战案例:网络请求超时自动重试的上下文管理器
场景:处理10GB日志文件 菜鸟写法(内存爆炸):
def read_file(path):
with open(path) as f:
return f.readlines()
for line in read_file('huge.log'):
process(line)老手套路:
def read_large_file(path):
with open(path) as f:
for line in f:
yield line
for line in read_large_file('huge.log'):
process(line)原理:
性能对比:处理100万行数据,生成器方案快4.3倍
场景:给所有API接口添加日志记录
菜鸟写法(重复代码):
def get_user():
print("Start get_user")
# 业务逻辑
print("End get_user")
def update_profile():
print("Start update_profile")
# 业务逻辑
print("End update_profile")老手套路:
def log_time(func):
def wrapper(*args, **kwargs):
print(f"Start {func.__name__}")
result = func(*args, **kwargs)
print(f"End {func.__name__}")
return result
return wrapper
@log_time
def get_user():
# 业务逻辑
@log_time
def update_profile():
# 业务逻辑原理:
进阶玩法:用functools.wraps保留元数据
场景:实现温度单位自动转换
菜鸟写法(冗余代码):
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def get_fahrenheit(self):
return self.celsius * 9/5 +32
def set_fahrenheit(self, value):
self.celsius = (value -32) *5/9老手套路:
class Celsius:
def __get__(self, instance, owner):
return instance._celsius
def __set__(self, instance, value):
instance._celsius = value
instance._fahrenheit = value *9/5 +32
class Fahrenheit:
def __get__(self, instance, owner):
return instance._fahrenheit
def __set__(self, instance, value):
instance._fahrenheit = value
instance._celsius = (value -32)*5/9
class Temperature:
celsius = Celsius()
fahrenheit = Fahrenheit()
t = Temperature()
t.celsius = 25 # 自动计算华氏度
print(t.fahrenheit) # 输出77.0原理:
应用场景:数据库ORM字段处理、单位转换、数据校验
15分钟训练计划:
掌握这些套路后,你会发现:Python编程就像搭积木,80%的日常需求都能用这些模式快速解决。剩下的20%?那是成为架构师的新起点!