7.3 Python代码示例
python
复制代码
from dataclasses import dataclass
from typing import Optional, List
import asyncio

@dataclass
class User:
    name: str
    age: int
    email: Optional[str] = None

def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.4f}s")
        return result
    return wrapper

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

@timer
def process_users(users: List[User]) -> dict:
    """使用字典推导式和条件表达式"""
    return {
        user.name: "adult" if user.age >= 18 else "minor"
        for user in users
        if user.email  # 只处理有邮箱的用户
    }

async def fetch_data(url: str) -> str:
    await asyncio.sleep(1)  # 模拟网络请求
    return f"Data from {url}"

async def main():
    urls = ["http://example.com/1", "http://example.com/2"]
    results = await asyncio.gather(*[fetch_data(url) for url in urls])
    print(results)

if __name__ == "__main__":
    users = [User("Alice", 30, "alice@example.com"),
             User("Bob", 15),
             User("Charlie", 35, "charlie@example.com")]
    
    print(process_users(users))
    
    fib = fibonacci()
    first_10 = [next(fib) for _ in range(10)]
    print(first_10)
    
    asyncio.run(main())