Python装饰器原理与实现代码
0
3
2026年6月12日
Python是最受欢迎的编程语言之一,语法优雅,生态强大。本文分享3个完整可运行的代码示例,涵盖Python核心开发技能。
完整装饰器工具集
装饰器增强函数功能,是Pythonic代码的标志。
import time
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function {func.__name__} took: {end - start:.4f}s")
return result
return wrapper
def log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling: {func.__name__}")
result = func(*args, **kwargs)
print(f" Return: {result}")
return result
return wrapper
@timer
@log
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(35))
完整上下文管理器
上下文管理器确保资源正确清理。
import time
from contextlib import contextmanager
class DatabaseConnection:
def __init__(self, db_name):
self.db_name = db_name
def __enter__(self):
print(f"Connecting to: {self.db_name}")
self.connection = f"Connection to {self.db_name}"
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"Closing: {self.db_name}")
self.connection = None
return False
@contextmanager
def timer_context(name="Block"):
start = time.time()
print(f"Starting: {name}")
try:
yield
finally:
end = time.time()
print(f"{name} completed in: {end - start:.4f}s")
with DatabaseConnection("mydb") as conn:
print(f"Using: {conn}")
with timer_context("Slow operation"):
time.sleep(0.5)
完整HTTP客户端
Requests库用于爬虫和自动化。
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
class HttpClient:
def __init__(self, timeout=10):
self.timeout = timeout
self.session = requests.Session()
retry = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
})
def get(self, url, params=None):
resp = self.session.get(url, params=params, timeout=self.timeout)
resp.raise_for_status()
return resp
client = HttpClient()
resp = client.get("https://httpbin.org/get", params={"key": "value"})
print(f"Status: {resp.status_code}")
Python最佳实践
- 遵循PEP 8,使用black格式化
- 使用虚拟环境隔离依赖
- 类型提示提升可读性
- Google风格文档字符串
- 捕获特定异常,不使用裸except
- 大数据使用生成器
- f-strings进行字符串格式化
技术分享,欢迎评论区交流讨论。
在线咨询
上一个应该是我,我买了一年,实在没价值,...