The problem: Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.該文用 OOP 實作, 程式如下 (摘錄自該文, 並加上 object):
class foo(object):
def __init__(self, n):
self.n = n
def __call__(self, i):
self.n += i
return self.n
我原本想到的作法是用 Closure, 寫好的版本如下:
def foo(n):
def inc(i):
inc.n += i
return inc.n
inc.n = n
return inc
目前還不知道使用 Closure 的適當時機, 總覺得包成 class 也 OK, 只是用 Closure 似乎簡潔一些。印象中 Aethanyc 曾說 Python 的 Closure 有些弱, 目前還沒什麼感覺, 待日後遇到應用情境時再說吧。
附帶一提, 我試用了 Google Prettify Code, 還不錯用。用法參見《用google prettify code给blogspot代码着色》。