python 延遲繫結(late binding)

2021-09-30 13:48:03 字數 1222 閱讀 6705

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

' a test module '

__author__ = 'zhang shuai'

defoperator

():return [lambda n: n * m for m in range(6)]

print([o(3) for o in operator()])

# 這是由於閉包函式引用的外部作用域的自由變數, 只有在內部函式被呼叫的時候才會搜尋變數m的值, 由於迴圈已結束, m指向最終值5, 所以各函式呼叫都得到了相同的結果。

# 即:

defoperator

():return [lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n,lambda m: 5 * n]

# 等價於

defoperator2

(): l =

for i in range(6):

deffunc

(m):

return m * i

return l

print([o(3) for o in operator2()])

# 改進

defoperator3

():return [lambda n, m=m: n * m for m in range(6)]

print([o(3) for o in operator3()])

# 這就相當於給每個函式乙個預設引數

# 即:

# def operator3():

# return [lambda n, m=0: m * n, lambda n, m=1: m * n, lambda n, m=2: m * n, lambda n, m=3: m * n,

# lambda n, m=4: m * n, lambda n, m=5: m * n]

defoperator4

(): l =

for i in range(6):

deffunc

(m, i=i):

return m * i

return l

print([o(3) for o in operator4()])

Python中的延遲繫結

延遲繫結出現在閉包問題中。下面我們看乙個閉包的例子 def gen mul n defmul x return n x return mul double gen mul 2 double value double 6 print double value 可以看出滿足閉包的幾點 閉包的優點 閉包的...

python 高階之路 繫結延遲

看看下面一題,試著寫出自己的答案。defmultipliers return lambda x i x for i in range 4 print m 2 for m in multipliers print type multipliers res 6,6,6,6 list 輸出結果不是我們想的...

Python閉包的延遲繫結

1.什麼是閉包,閉包必須滿足以下3個條 2.閉包的優點def add a def add b return a b return add ad 2 2 計算2 2的值,用類實現的話,相對麻煩 閉包使用nonlocal deftester start state start defnested lab...