python 装饰器用法

pythont天坑

装饰器

  • 定义装饰器
def demo(func):
    print("1111111")

    def wrapper(*args, **kwargs):
        print("2222222")
        return func()
    print("3333333")
    return wrapper

  • 使用装饰器
@demo
def test_wrapper():
    """测试装饰器"""
    print("4444444")
    pass
  • 装饰器执行流程
1111111
3333333
2222222
4444444
  • 使用装饰器注意点
    • 未使用装饰器前,函数对象名字及文档打印结果如下
      print(test_wrapper.__name__)
      print(test_wrapper.__doc__)
      
      test_wrapper
      测试装饰器
    
    • 使用装饰器会改变函数对象的一些特性,名字以及文档
      @demo
      def test_wrapper():
          """测试装饰器"""
          pass
      
      
      # test_wrapper()
      print(test_wrapper.__name__)
      print(test_wrapper.__doc__)
      
      wrapper
      None
    
      
    
    • 引入functools中的wraps解决
      from functools import wraps
      def demo(func):
          @wraps(func)
          def wrapper(*args, **kwargs):
              return func()
          return wrapper
    
    
      @demo
      def test_wrapper():
          """测试装饰器"""
          pass
      
      
      # test_wrapper()
      print(test_wrapper.__name__)
      print(test_wrapper.__doc__)
      
      
      运行结果
      test_wrapper
      测试装饰器
    
      
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
装饰器Python 中一个非常强大的特性,它可以用来修改或增强函数或类的功能。装饰器本质上是一个函数,可以接收一个函数或类作为参数,并返回一个新的函数或类。装饰器通常用于在不修改函数或类本身的情况下,增加一些额外的功能或修改其行为。以下是一些常见的 Python 装饰器用法示例: 1. 函数装饰器 ```python def my_decorator(func): def wrapper(): print("Before function is called.") func() print("After function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() ``` 输出结果: ``` Before function is called. Hello! After function is called. ``` 在这个例子中,我们定义了一个名为 `my_decorator` 的函数装饰器,它接收一个函数作为参数,并返回一个新的函数 `wrapper`。在 `wrapper` 函数中,我们添加了一些额外的代码,用于在函数调用之前和之后执行一些操作。然后,我们使用 `@my_decorator` 语法来装饰 `say_hello` 函数,使其在被调用时自动被 `my_decorator` 装饰器修饰。最后,我们调用 `say_hello` 函数,它会自动执行 `my_decorator` 装饰器中定义的操作。 2. 类装饰器 ```python class MyDecorator: def __init__(self, func): self.func = func def __call__(self): print("Before function is called.") self.func() print("After function is called.") @MyDecorator def say_hello(): print("Hello!") say_hello() ``` 输出结果: ``` Before function is called. Hello! After function is called. ``` 这个例子中,我们定义了一个名为 `MyDecorator` 的类装饰器,它接收一个函数作为参数,并重载了 `__call__` 方法。在 `__call__` 方法中,我们添加了一些额外的代码,用于在函数调用之前和之后执行一些操作。然后,我们使用 `@MyDecorator` 语法来装饰 `say_hello` 函数,使其在被调用时自动被 `MyDecorator` 装饰器修饰。最后,我们调用 `say_hello` 函数,它会自动执行 `MyDecorator` 装饰器中定义的操作。 3. 带参数的装饰器 ```python def repeat(num): def my_decorator(func): def wrapper(): for i in range(num): print("Before function is called.") func() print("After function is called.") return wrapper return my_decorator @repeat(num=3) def say_hello(): print("Hello!") say_hello() ``` 输出结果: ``` Before function is called. Hello! After function is called. Before function is called. Hello! After function is called. Before function is called. Hello! After function is called. ``` 在这个例子中,我们定义了一个名为 `repeat` 的装饰器工厂函数,它接收一个参数 `num`,并返回一个新的函数装饰器 `my_decorator`。在 `my_decorator` 装饰器中,我们定义了一个新的函数 `wrapper`,它会重复执行被装饰的函数 `num` 次。然后,我们使用 `@repeat(num=3)` 语法来装饰 `say_hello` 函数,使其在被调用时自动被 `repeat` 装饰器修饰,并传递参数 `num=3`。最后,我们调用 `say_hello` 函数,它会自动执行 `repeat` 装饰器中定义的操作,重复执行 `say_hello` 函数三次。 以上是 Python 装饰器的一些常见用法装饰器Python 中非常强大的特性,可以用于各种场景,如日志记录、性能分析、缓存处理等。学会使用装饰器可以让你的代码更加简洁、易读和易于维护。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值