deftimer(func): """计算函数执行时间的装饰器""" import time defwrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} executed in {end-start:.4f} seconds") return result return wrapper
@timer deflong_running_func(): import time time.sleep(1)
long_running_func() # 输出执行时间
生成器函数
使用yield返回值的函数:
1 2 3 4 5 6 7 8
deffibonacci(limit): a, b = 0, 1 while a < limit: yield a a, b = b, a + b
for num in fibonacci(100): print(num) # 0 1 1 2 3 5 8 13 21 34 55 89
三、模块化编程
模块导入
导入整个模块
1 2
import math print(math.sqrt(16)) # 4.0
导入特定函数/类
1 2
from math import sqrt, pi print(sqrt(9)) # 3.0
导入并重命名
1 2
import numpy as np from math import factorial as fact
相对导入(在包内部)
1 2
from . import module_name # 当前目录 from .. import module_name # 上级目录
# 不好 defprocess_data(data): # 清洗数据 cleaned = [] for item in data: cleaned.append(item.strip()) # 分析数据 total = sum(cleaned) average = total / len(cleaned) return average
# 更好 defclean_data(data): return [item.strip() for item in data]
defanalyze_data(data): total = sum(data) return total / len(data)
# 使用 cleaned = clean_data(raw_data) result = analyze_data(cleaned)
DRY原则(Don’t Repeat Yourself)
避免重复代码,通过函数封装复用:
1 2 3 4 5 6 7 8 9 10 11 12
# 重复代码 print("=" * 50) print("Welcome to the system") print("=" * 50)
deffactorial(n): """ 计算阶乘 >>> factorial(5) 120 >>> factorial(0) 1 """ if n == 0: return1 return n * factorial(n - 1)
if __name__ == "__main__": import doctest doctest.testmod()
使用logging调试
1 2 3 4 5 6 7 8 9
import logging
logging.basicConfig(level=logging.DEBUG)
defcomplex_calculation(x): logging.debug(f"Starting calculation with x={x}") result = x ** 2 + 2 * x + 1 logging.debug(f"Calculation complete, result={result}") return result