闭包及装饰器
Posted python-beginner
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了闭包及装饰器相关的知识,希望对你有一定的参考价值。
#_*_coding:utf-8_*_
#作者:王佃元
#日期:2019/12/23
# 装饰器:decorator
# 闭包函数:函数块 + 定义函数时的环境。内部函数引用外层函数的变量
# def outer():
# x = 10
# # print(x, id(x))
#
# def inner():
# print(x, inner)
# return inner
#
#
# f = outer()
# print(f)
# f()
# def show_time(f):
# def inner():
# start = time.time()
# f()
# end = time.time()
# print(‘spend %s‘ % (end - start))
# return inner
# @show_time
# def foo():
# print(‘foo.......‘)
# time.sleep(2)
#
#
# def bar():
# print(‘bar.......‘)
# time.sleep(3)
#
#
# foo = show_time(foo)
# foo()
import time
def log(flag=‘‘):
def show_time(f):
def inner(*a, **b):
start = time.time()
f(*a, **b)
end = time.time()
print(‘spend %s‘ % (end - start))
if flag == ‘true‘:
print(‘日志记录‘)
else:
print(‘错误信息‘)
return inner
return show_time
@log(‘true‘) # foo = log(true) show_time
def foo(*arg, **args):
sum1 = 0
for i in arg:
sum1 += i
print(sum1)
time.sleep(2)
foo(1, 2, 4)
@log()
def bar():
print(‘bar.......‘)
time.sleep(3)
以上是关于闭包及装饰器的主要内容,如果未能解决你的问题,请参考以下文章