Real Problems with Python

Neel Krishnaswami neelk at brick.cswv.com
Sun Feb 13 16:53:35 EST 2000


Alex <alex at somewhere.round.here> wrote:
> 
> > > Couldn't we approximate lexical scoping with classes?
> 
> Could someone give me an example of how to do this?  Probably I am
> simply confused about the terminology, but don't you run into the same
> sorts of namespace problems with nesting classes as you do with nesting
> functions? 

Certainly; here's a teeny closure in Scheme:

  (define make-adder
    (lambda (n)
      (lambda (x) (+ n x))))
  
  (define add-three (make-adder 3))
  
  (add-three 6)
  
  -> 9
  
  (add-three 9)
  
  -> 12

And here's the Python equivalent, using classes:

  >>> class Adder:
  ... 	def __init__(self, n):
  ... 	    self.n = n
  ... 	def __call__(self, x):
  ... 	    return self.n + x
  ...
  >>> add_three = Adder(3)
  >>> add_three(6)
  9
  >>> add_three(9)
  12

Basically, you use the __call__ method to let instances use the
function call syntax. 


Neel



More information about the Python-list mailing list