python全棧學習--day11(函數進階應用程式)

來源:互聯網
上載者:User

標籤:src   說明   索引值   實現   執行   就是   字典   引用   檢測   

一,函數名是什嗎?

  函數名是函數的名字,本質:變數,特殊的變數。

  函數名()執行此函數

‘‘‘在函數的執行(調用)時:打散。    *可迭代對象(str,tuple,list,dict(key))每一個元素添加到args元組中。    **dict 將字典的索引值對添加到kwargs字典中。在函數的定義時: 彙總。    *args將所有的位置參數彙總到一個元組中。    **kwargs 將所有的關鍵字參數彙總到一個字典中。‘‘‘

  #python 2 沒有nonlocal

1.單獨列印函數名 

def func1():    print(666)print(func1)

  執行輸出:#(單獨列印函數名為函數的記憶體位址)

2. 函數名的賦值:

def func2():    print(666)f = func2print(f())

      #說明:這裡主要告訴你的是函數名是可以賦值的。這裡其實是沒有傳回值的,所以為None,而666 只是函數體內的print

3. 函數名可以作為容器類資料的元素

案例一:

def f1():    print(1211)def f2():    print(1222)def f3():    print(1233)def f4():    print(1233)f1()f2()f3()f4()

  執行後輸出:

說明:這裡是不是很麻煩呢?這裡每一次使用都要寫一個函數?這樣豈不是還是有重複性的代碼呢?

案例二:(這裡實現一個最簡單的應用)

def f1():    print(1211)def f2():    print(1222)def f3():    print(1233)def f4():    print(1233)l1 = [f1,f2,f3,f4]for i in l1:    i()

  

4 函數名可以作為參數。

def f1():    print(666)def f2(x):    x()f2(f1)

  

解析:

a = 1def f1(x):  #2. 這裡這個時候f1(1)    print(x)   # 3.列印f1的形參f1(a)  #1,將變數a =1 的值 1傳入f1中

  執行後輸出:1

5.函數名可以作為函數的傳回值

def f11(x):  #2.第二步形參得到實參傳入的值為:5
return x #3. 第三步返回給函數調用者 f11(5)

ret = f11(5) # 1.第一步將5傳入函數 f11中
print(ret)

#閉包

#閉包:就是內層函數對外層函數(非全域)變數引用

#執行個體一:將內層函數的666在外層列印出來
def wraaper():
def inner():
print(666)
inner()
wraaper()

#列印後輸出:666
#方法二:
def wraaper():
def inner():
print(666)
return inner
wraaper()()

 #如何檢測閉包

def wraaperl():    name = ‘老男孩‘    def inner():        print(name)    inner()    print(inner.__closure__) #cell  如何這裡i為none 就是不是閉包# wraaperl()

  #如何判斷 內層函數名.__closure__ cell 就是閉包

  閉包:當函數開始執行時,如果遇到了閉包,他有一個機制,他會永遠開闢一個記憶體空間,將閉包變數等值放入其中,不會隨著函數的執行完畢而消失

 

 裝飾器的初始:

 

 

def add_b():    b = 42    def do_global():        b = 10        print(b) # 1.10        def dd_nonlocal():            nonlocal b            b = b + 20            print(b)  # 2.30        dd_nonlocal()        print(b)  # 3.30    do_global()    print(b) # 4.42add_b()

 

 

 

 

python全棧學習--day11(函數進階應用程式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.