網頁

2015年6月28日 星期日

[Python] bind

主題:想要對Python的function有bind的能力


簡介:

C++, javascript裡面都叫bind但在python則由functools的partial完成。

什麼是bind ?
就是"綁定", 綁定什麼 ? 讓你的func參數的parameter綁定某些值。

相信看完下面的範例就會有感覺

Example:

#!/usr/bin/python3

from functools import partial

def myfunc(x, y, z):
        print ("%r %r %r" % (x,y,z))

binded_myfunc = partial(myfunc, 2, 3, 4)

myfunc(1,2,3)

binded_myfunc()

結果:
1 2 3
2 3 4


沒有留言:

張貼留言