python 你会装饰器吗


现在找工作黄金时间,作为一个测试,经常被面试官问到,什么是装饰器,或者你对装饰器了解多少?

抛出一个问题,而只会回答,装饰器是装饰函数的,通常是提升函数功能,返回一个函数。然后继续深入问问的话,就自己把自己说挂了。

装饰器:

装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。他们有助于让我们的代码更简短,也更Pythonic(Python范儿)。大多数初学者不知道在哪儿使用它们,所以我将要分享下,哪些区域里装饰器可以让你的代码更简洁。

在网上找资料,发现这个 https://www.runoob.com/w3cnote/python-func-decorators.html 讲python的装饰器讲的非常清楚。以下是个人的一些理解。

(1)无参数的装饰器

例如,我们需要打印log 和打印出这个 函数执行时间 那么就可以利用这个装饰器的功能。简洁的代码,也实现了我们的要求。

时间装饰器

def time_consume(function):
"""时间消耗计时器"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
begin_time = datetime.now()
check = function(*args, **kwargs)
end_time = datetime.now()
print(end_time - begin_time)
return check

return wrapper


log装饰器

def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called python zhuangshiqi"
print(log_string)
# 打开logfile,并写入内容
with open(logfile, 'a') as opened_file:
# 现在将日志打到指定的logfile
opened_file.write(log_string + '\n')
return func(*args, **kwargs)

return wrapped_function




(2)有参数的装饰器

例如我们在做接口自动化测试的时候,需要写自动化测试用例,而最后一步就是生成测试报告和发送邮件,那么就可以使用装饰器的功能,写一个公共函数。

生成测试报告
def UI_Report(testcase,ReportPath):
"""
根据传入的testcase 来判断执行哪种报告生成方式。
"""

def Report(s):
@wraps(s)
def creat_report():
AA = hasattr(testcase, '__call__')
# AA = isfunction(testcase)
if AA:
print '这个是函数'
suite = unittest.makeSuite(testcase)
fp = file(ReportPath, 'wb')
runner = HTMLTestRunner(stream=fp, title=r'UI自动化', description=r'接口自动化测试报告')
runner.run(suite)
fp.close()
else:
print '不是函数,是执行run_main方法'
fp = file(ReportPath, 'wb')
runner = HTMLTestRunner(stream=fp, title=r'UI自动化测试报告', description=r'商城')
runner.run(testcase)
fp.close()

return creat_report

return Report


我装饰器中增加了一个判断,那是因为,如果直接执行unitest用例的时候,是需要用到suite 测试套件 而
suite = unittest.makeSuite(testcase)  这个testcase 就是你的 类名 他实质上 是一个函数。

而 我们写了一个run_main 函数 来通过 文件名称共性来执行 多个用例文件 ,此时这个testcase 就不是一个 函数

所以根据不同的testcase 来执行不同的报告,这里还增加了一个参数是 path 也可以写死。

有路径的log装饰器

def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called python zhuangshiqi"
print(log_string)
# 打开logfile,并写入内容
with open(logfile, 'a') as opened_file:
# 现在将日志打到指定的logfile
opened_file.write(log_string + '\n')
return func(*args, **kwargs)

return wrapped_function

return logging_decorator


 

相关