代碼中的 f 指的是在什么?參數‘ms’的傳遞路徑又是怎樣的呢?求大神解答??
代碼中的 f 指的是在什么?參數‘ms’的傳遞路徑又是怎樣的呢?求大神解答?
import time
def performance(unit):
? ? def log_time(f):
? ? ? ? def a(*args,**kw):
? ? ? ? ? ? t1=time.time()
? ? ? ? ? ? r=f(*args,**kw)
? ? ? ? ? ? t2=time.time()
? ? ? ? ? ? if unit == 's':
? ? ? ? ? ? ? ? t=t2-t1;
? ? ? ? ? ? elif unit == 'ms':
? ? ? ? ? ? ? ? t=(t2-t1)*1000;
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? print 'input error'
? ? ? ? ? ? print 'call %s() in %f %s' %(f.__name__,t,unit);
? ? ? ? ? ? return r
? ? ? ? return a
? ? return log_time
? ? ? ? ? ??
@performance('ms')
def factorial(n):
? ? return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
2020-08-15
f指的就是被裝飾器裝飾的函數,就是你那段代碼里的factorial()函數,factorial()函數被performance這個裝飾器裝飾了
2020-04-11
'ms'傳給performance后存儲在函數performance的作用域中,f傳給log_time后存儲在log_time作用域中,而a隸屬于以上兩個函數的作用域。
在調用performance('ms')后返回了一個unit參數為'ms'的log_time裝飾器,相當于@log_time,然后傳入factorial函數作為log_time裝飾器的參數,返回的函數a即為f參數為factorial,unit參數為'ms'的包裝后的factorial函數,然后再對factorial函數進行調用,則為帶著unit='ms'和f=factorial進行調用。