裝飾器_一(Pyhton中的閉包)

· 閉包

閉包是什麼:
如果在一個函數中,定義了另外一個函數,並且那個函數使用了外函數的變量,並且外邊那個函數返回了裏邊這個函數的引用。那麼稱爲裏邊的這個函數爲閉包。例如:

def greater(name):
    def say_hello():
        print('hello my name is %s' % name)
    return say_hello

   hello = greater('as')
   hello()

閉包對於我們到底有什麼用?
用閉包實現一個計算器的加減乘除:

def calculator(option):
    if option == 1:
        def add(x, y):
            return x + y
        return add
    if option == 2:
        def minus(x, y):
            return x - y
        return minus
    if option == 3:
        def multipy(x, y):
            return x * y
        return multipy
    if option == 4:
        def divide(x, y):
            return x / y
        return divide
    else:
        print('操作符不正確')

add = calculator(1)
print(add(1, 3))
print(add(1, 4))
multipy = calculator(3)
print(multipy(1, 5))
print(multipy(2, 5))
nonlocal關鍵字:
    如果想要修改外面函數的變量,這時候應該用nolocal關鍵字,來把這個變量標示爲外面函數的變量:
    以下代碼修改了name,使用了nonlocal關鍵字,不會報錯:
def greet(name):
    print('outer name is %s' % name)
    def say_hello():
        nonlocal name
        name = 'China_' + name
        print('inter name is %s' % name)
    return say_hello

greet('HK')()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章