Python装饰器用法详解与实例代码分享

下载需积分: 5 | ZIP格式 | 4KB | 更新于2025-01-04 | 132 浏览量 | 0 下载量 举报
收藏
资源摘要信息:"装饰器是Python编程语言中的一个高级特性,它允许用户在不修改函数或类的代码的情况下,增加其功能。装饰器本质上是一个函数,它接受一个函数作为参数并返回一个新的函数。装饰器可以应用于任何可调用的对象,如函数和类的方法。在实际应用中,装饰器可以用来增加日志记录、访问控制、缓存、事务处理等众多功能。 以下是几种不同情形下装饰器的示例代码,这些代码片段通常在学习和使用装饰器时很有帮助。 1. 基础装饰器 ```python def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper def say_hello(): print("Hello!") say_hello = my_decorator(say_hello) say_hello() ``` 2. 使用`@decorator`语法糖 ```python def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() ``` 3. 装饰带有参数的函数 ```python def my_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @my_decorator def say_hello(name): print(f"Hello {name}!") say_hello("Alice") ``` 4. 装饰带有返回值的函数 ```python def my_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @my_decorator def say_hello(name): return f"Hello {name}!" print(say_hello("Alice")) ``` 5. 带有参数的装饰器 ```python def repeat(num_times): def decorator_repeat(func): def wrapper(*args, **kwargs): for _ in range(num_times): result = func(*args, **kwargs) return result return wrapper return decorator_repeat @repeat(num_times=3) def greet(name): print(f"Hello {name}!") greet("Alice") ``` 6. 装饰器的装饰器 ```python def decorator_with_args(decorator_arg1, decorator_arg2): def decorator(func): def wrapper(*args, **kwargs): print(f"Decorator arguments: {decorator_arg1}, {decorator_arg2}") return func(*args, **kwargs) return wrapper return decorator @decorator_with_args(decorator_arg1='Hello', decorator_arg2='World') def say_hello(name): print(f"Hello {name}!") say_hello("Alice") ``` 这些代码示例覆盖了装饰器的一些基本用法和较为复杂的应用场景。了解并掌握这些知识点有助于提升Python编程能力,特别是在处理函数式编程模式和代码复用方面。详细说明上述代码的功能和用法,将有助于读者更好地理解和应用装饰器。"

相关推荐