これは、Python の標準ライブラリである inspect.py の例です。それは現在読んでいます
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
else:
return convert(object)
これは、convert 関数と join 関数をパラメーターとして持ち、リストとタプルを再帰的に走査します。再帰は、最初のパラメーターが関数である map() を使用して実装されます。このコードは、Python でのクロージャのサポートよりも前のものであるため、convert と join を再帰呼び出しに渡すために、2 つの追加のデフォルト引数が必要です。クロージャーを使用すると、これは次のようになります
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o: strseq(o, convert, join), object))
else:
return convert(object)
OO 言語では、オブジェクトを使用して状態とバインドされたメソッドを渡すことができるため、通常、クロージャーはあまり使用しません。Python にクロージャがなかったとき、Python はオブジェクトでクロージャをエミュレートするのに対し、Lisp はクロージャでオブジェクトをエミュレートすると人々は言いました。IDLE (ClassBrowser.py) の例:
class ClassBrowser: # shortened
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", self.close)
ここで、self.close は、Escape が押されたときに呼び出されるパラメーターなしのコールバックです。ただし、close 実装にはパラメーターが必要です。つまり、self、次に self.top、self.node です。Python にメソッドがバインドされていない場合は、次のように記述できます。
class ClassBrowser:
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", lambda:self.close())
ここで、ラムダはパラメーターからではなく、コンテキストから「自己」を取得します。