一、装饰器(Decorators)

装饰器是 Python 的高级特性,用于修改函数行为而无需更改其代码。常用场景包括日志记录、权限验证等。

  • 使用 @decorator 语法
  • 通过函数嵌套实现
  • 示例:
    def my_decorator(func):
        def wrapper():
            print("Before function call")
            func()
            print("After function call")
        return wrapper
    
    @my_decorator
    def say_hello():
        print("Hello!")
    
Python_decorator

二、生成器(Generators)

生成器通过 yield 关键字实现,适用于处理大量数据时节省内存。

  • 与普通函数的区别:逐条生成数据而非一次性返回列表
  • 示例:
    def count_up_to(n):
        count = 1
        while count <= n:
            yield count
            count += 1
    
    使用 for 循环遍历生成器输出:
    for number in count_up_to(5):
        print(number)
    
Python_generator

三、上下文管理器(Context Managers)

通过 with 语句管理资源,确保文件或网络连接等操作的正确关闭。

  • 示例:
    with open("file.txt", "r") as file:
        content = file.read()
    
  • 自定义上下文管理器:
    class MyContextManager:
        def __enter__(self):
            print("Entering context")
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("Exiting context")
    
Python_context_manager

四、扩展阅读 📚

想深入了解 Python 高级特性?可以查看本站的Python 核心特性详解教程,涵盖更多进阶内容!