標籤:nbsp 順序 代碼 運行 條件 list start 作用 ima
python裝飾器
裝飾器本質上是一個函數,在不對其他函數原始碼進行修改的情況下,為其他函數提供額外功能。
import time
def test1():
time.sleep(3)
print(‘in the test1‘)
def test2():
time.sleep(3)
print(‘in the test2‘)
def timer(func): #就是返回deco函數的記憶體位址
def deco():
stime=time.time()
func()
ptime=time.time()
print(‘the func run time is %s‘%(ptime-stime))
return deco #返回deco函數的記憶體位址(記憶體位址加小括弧即為函數)
test1=timer(test1)
test1()
分析:test1的記憶體位址(只有函數名,沒有小括弧就是指其記憶體位址)賦值給func,func()就等價與test1()運行,deco記錄test1()運行相關時間
二:高階函數
滿足下列條件之一就可成函數為高階函數
某一函數名當做參數傳入另一個函數中
函數的傳回值包含n個函數,n>0
高階函數示範:
| 123456 |
def bar(): print ‘in the bar‘def foo(func): res=func() return resfoo(bar) |
高階函數的牛逼之處
| 12 456789 |
def foo(func): return func print ‘Function body is %s‘ %(foo(bar))print ‘Function name is %s‘ %(foo(bar).func_name)foo(bar)()#foo(bar)() 等同於bar=foo(bar)然後bar()bar=foo(bar)bar() |
三:內嵌函數和變數範圍:
定義:在一個函數體內建立另外一個函數,這種函數就叫內嵌函數(基於python支援靜態嵌套域)
函數嵌套示範:
| 12345678 |
def foo(): def bar(): print ‘in the bar‘ bar() foo()# bar() |
局部範圍和全域範圍的訪問順序
| 1234567891011 |
x=0def grandpa(): # x=1 def dad(): x=2 def son(): x=3 print x son() dad()grandpa() |
局部變數修改對全域變數的影響
| 12345678910111213141516171819202122 |
y=10# def test():# y+=1# print y def test(): # global y y=2 print y test()print y def dad(): m=1 def son(): n=2 print ‘--->‘,m + n print ‘-->‘,m son()dad() |
四:閉包:
如果在一個內建函式裡,對在外部範圍(但不是在全域範圍)的變數進行引用,那麼內建函式就被認為是 closure
| 12345678910111213 |
def counter(start_num=0): count=[start_num] def incr(): count[0]+=1 return count[0] return incr print counter()print counter()()print counter()()c=counter()print c()print c() |
python學習之路day6