python學習之路day6

來源:互聯網
上載者:User

標籤: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()運行相關時間

二:高階函數

滿足下列條件之一就可成函數為高階函數

  1. 某一函數名當做參數傳入另一個函數中

  2. 函數的傳回值包含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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.