码迷,mamicode.com
首页 > 其他好文 > 详细

闭包及装饰器

时间:2019-12-25 23:44:08      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:art   +=   time   decorator   print   闭包   tor   foo   pre   

#_*_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)

闭包及装饰器

标签:art   +=   time   decorator   print   闭包   tor   foo   pre   

原文地址:https://www.cnblogs.com/python-beginner/p/12099512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!