Python装饰器入门:零基础也能进阶测试开发!

装饰器在python里是一个比较好用的功能,可以比较方便的封装自定义的函数和实现,很适合在自动化用例的脚本中扩充公共的方法去使用。同时整体门槛不高,易于理解,对新手友好。下面来进行一下说明阐述。

装饰器(Decorator)是一种设计模式,用于修改或增强其他函数的功能。装饰器通过在不修改原始函数代码的情况下,给函数添加新的功能。

装饰器本质上是一个函数,它接受一个函数作为参数并返回一个新的函数。Python 中使用 @decorator_name 语法来应用装饰器。

1. 基本装饰器示例

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()

在这个例子中,my_decorator 是一个装饰器,它接受一个函数 ,func 作为参数,并返回一个新的函数 

wrapper。wrapper 函数在调用 func 之前和之后添加了一些额外的行为。say_hello 函数被 my_decorator 装饰,因此在调用 say_hello 时,实际上调用的是 my_decorator 返回的 wrapper 函数。

输出:​​​​​​​

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

2. 参数化装饰器示例

装饰器也可以接受参数,成为参数化装饰器。这可以通过在装饰器外层再包装一层函数来实现:​​​​​​​

def repeat(times):
  def decorator(func):
      def wrapper():
          for _ in range(times):
              func()
      return wrapper
  return decorator
@repeat(times=3)
def say_hello():
  print("Hello!")
say_hello()

输出:​​​​​​​

Hello!
Hello!
Hello!

3. 使用 functools.wraps 的装饰器

Python 标准库 functools 提供了一些有用的工具,如 wraps 装饰器,它用于保留被装饰函数的元数据:

使用 wraps 可以保留原始函数的 __name__、__doc__ 等属性,这对于调试和元编程非常有用。​​​​​​​

from functools import wraps
def my_decorator(func):
  @wraps(func)
  def wrapper():
      print("Before the function call.")
      func()
      print("After the function call.")
  return wrapper  
@my_decorator
def say_hello():
  """Greet the user."""
  print("Hello!")
say_hello()
print(say_hello.__name__)
print(say_hello.__doc__)

输出:​​​​​​​

Before the function call.
Hello!
After the function call.
say_hello
Greet the user.

以上示例都可以嵌入自己自定义的自动化框架中,来辅助自己封装公共方法,提高书写和执行效率。

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值