51Testing软件测试论坛

标题: 装饰器的简单使用 [打印本页]

作者: ufoofuufoofu    时间: 前天 21:21
标题: 装饰器的简单使用
      装饰器是一种功能很强大的模式,通常用于在不对原函数改动时以获取运行时间、日期等,但实际应用时往往能获得许多有意思的结果。比如我们先设一个过滤器用于在某个函数运算结束时对结果进行过滤处理。
  1. def filter_shell(filterfunc):
  2.     def wrapper1(func):
  3.         @functools.wraps(func)
  4.         def wrapper2(*args,**kwargs):
  5.             res1=func(*args,**kwargs)
  6.             res2=filterfunc(res1)#filterfunc函数进行数据过滤
  7.             return res2
  8.         return wrapper2
  9.     return wrapper1
复制代码

    然后再定义一个过滤函数。
  1. def ip_filter(info:list)->str:#print2data
  2.     for line in info:
  3.         if 'inet addr' in line:
  4.           ip=line2ip(line)
  5.           break
  6.     return ip
复制代码
定义一个调用函数。
  1. @filter_shell(ip_filter)
  2. def wss_get_data(netip:str,cardip:str,is_drop:str)->str:
  3.     with g_login(netip,22,'root','root') as conn:
  4.         with CardOp(conn) as t:
  5.           cfg=t.card_op(cardip,9002,['ifconfig\r'])  
  6.     return cfg
复制代码
通过这样的调用,可以从获取的大段信息中提取自己想要的部分内容。同时如果过滤函数不能先行确定的话,也可以用一种连续调用的方式,就像剥洋葱一样。
  1. filter_shell(ip_filter)(wss_get_data)(*args)
复制代码
这一样可以达到目的,但一旦出故障定位起来十分麻烦,尽量不要这样写。






欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2