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代码着色》。
PEP 3104 (http://www.python.org/dev/peps/pep-3104/#new-syntax-in-the-binding-outer-scope), already implemented in python3, introduced the new 'nonlocal' keyword to allow modifying a variable in an outer scope.
回覆刪除Thus the 'weirdness' regarding Python's closures is a thing of the past.
When pass first class functions around as data, having closures is often more convenient then having to implement __call__() on a class, no?
用 closure @.@
回覆刪除(def a
(let [a (atom 0)]
#(swap! a inc)))
(a) ; 傳回1
(a) ; 傳回2
(a) ; 傳回3