python中的閉包

  • 閉包

綁定外部變量的函數

返回一個綁定外部變量的內部函數

  1. 嵌套函數

  2. 內部函數用到了外部變量

  3. 外部函數返回內部函數


def pow_x(x):
    def echo(value):
        x=2
        return value ** x
    return echo

if __name__=='__main__':
    lst = (pow_x(2), pow_x(3), pow_x(4))
    for p in lst:
        print p(2)
  1. 內部變量不能"改變"外部變量

  2. 內部函數用到了外部變量爲list,則可以從外部或內部改變值,並且即使外部沒有引用也不會回收

    例子


#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'teng'
def pow_y(x):
    def echo(value):
        x[0] = x[0]*2 # 可以改變值 訪問了該值 而不是給予
        # x=[2,2]
        return value ** x[0], value**x[1]
    return echo


if __name__ == '__main__':
    lst2 = pow_y([1, 1])
    print "closure powy", lst2(2)
    print "closure powy", lst2(3)
    print "closure powy", lst2(4)

一個關於閉包的應用 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'teng'

origin = [0, 0]
legal_x = [0, 50]
legal_y = [0, 50]

def create(pos):
    def player(direction, step):
        new_x = pos[0]+direction[0]*step
        new_y = pos[1]+direction[1]*step
        pos[0] = new_x
        pos[1] = new_y
        return pos
    return player

player1 = create(origin[:])
print player1([1, 0], 10)
print player1([0, 1], 20)
print player1([-1, 0], 10)
print "orgin is", origin

print "origin is",origin

player2 = create(origin[:])
print player2([-1,0],10)
print player2([1,1],20)
print player2([1,0],10)


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