程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

5、 Python learning notes - functions - decorator (2)

編輯:Python
# Decorator exercise
""" requirement
1、 The function function implements the addition of two integer elements , also sleep 2 second
2、 Print function execution time through decorator
3、 The decorator determines whether to record logs according to parameters
"""
""" analysis
1、 The first two requirements have been fulfilled before , Don't say it again .
2、 The third requirement requires us to pass a flag bit flag, Essence of decorator @Bar be equal to foo=Bar(foo), There is no place to pass parameters .
And because of the open and closed principle , Nor can we modify function functions .
So we need to nest another layer of functions , To receive the pass parameters , Then return the function Bar, In effect @Bar Plus transfer parameters
"""
import time
def logger(flag):
def bar(foo):
def inter(a, b):
start_time = time.time()
foo(a, b)
end_time = time.time()
print(' execution time {}'.format(end_time - start_time))
if flag == 'Y':
print(' Log ')
return inter
return bar
@logger('Y') # Because of the function logger The return value of Bar, In fact, it is to execute the function first logger( because logger There's... In the back ‘()’ Of , Is to call this function ), Set up flag = ‘y’, And then execute @Bar
def foo(a, b):
time.sleep(2)
print(a + b)
foo(3, 4)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved