# 🚀 Python 高级技巧

本页面介绍 Python 编程中的高级应用技巧。

# 🎯 高级功能

# 1. 装饰器

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"执行时间: {time.time() - start:.2f}秒")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

# 2. 上下文管理器

class ExcelManager:
    def __init__(self, filename):
        self.filename = filename
        self.workbook = None

    def __enter__(self):
        from openpyxl import load_workbook
        self.workbook = load_workbook(self.filename)
        return self.workbook

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.workbook:
            self.workbook.close()

# 使用
with ExcelManager('data.xlsx') as wb:
    ws = wb.active
    print(ws['A1'].value)

# 3. 并行处理

from concurrent.futures import ThreadPoolExecutor
import pandas as pd

def process_file(filepath):
    df = pd.read_excel(filepath)
    # 处理逻辑
    return df

with ThreadPoolExecutor(max_workers=4) as executor:
    results = list(executor.map(process_file, filepaths))

# 📚 相关资源

Last Updated: 4/23/2026, 9:22:28 AM