Python 2.0

Hisao Suzuki suzuki611 at okisoft.co.jp
Mon Jun 7 20:18:13 EDT 1999


In article <14172.6652.550882.854800 at bitdiddle.cnri.reston.va.us>,
Jeremy Hylton <jeremy at cnri.reston.va.us> wrote:
| >>> (let ((sum 0))
|        (let ((add (lambda (x) (set! sum (+ sum x))))
|              (sub (lambda (x) (set! sum (- sum x)))))
|                 (add 2)
|                 (add 3)
|                 (sub 1)
|              sum))
| 4

A bound method is equivalent to a closure (or rather a function
with its own environment) in a certain sense.  The `self'
parameter serves as the environment.

The traditional (or good old :-) translation of the above code
would be like this:

def alsoWorks():
    class _alsoWorks_t:
	def add(self, x): self.sum = self.sum + x
	def sub(self, x): self.sum = self.sum - x
    i = _alsoWorks_t()
    i.sum = 0
    i.add(2)
    i.add(3)
    i.sub(1)
    return i.sum

--===-----========------------- Sana esprimo naskas sanan ideon.
SUZUKI Hisao            suzuki611 at okisoft.co.jp, suzuki at acm.org.




More information about the Python-list mailing list