Simple Function Question

Sean Blakey sblakey at freei.com
Wed Apr 26 15:10:12 EDT 2000


def make_incrementer(n):
     def increment(x, n=n):
         return x+n
     return increment

When you call make_incrementer with an argument of 1, the first thing
make_incrementer does is defina a new function, increment.  

Increment takes two arguments, x and n.  n defaults to the same value n
has in make_incrementer (1).  Since n has a default value, increment can
be called as a one-argument function that simply returns whatever it is
called with(x) + 1.

make_incrementer then returns this function.  This is the tricky part:
the return value of the make_incrementer function is itself a function.
When this function is called with one argument, that function becomes x
in increment().  If that function is called with two arguments, the two
arguments will become x and n.

Some people find the OO version of this easier to understand.  Perhaps
this will help:
>>>class Incrementer:
>>>	def __init__(self, increment_amount):
>>>		self.increment_amount = increment_amount
>>>	def increment(self, value):
>>>		return value + self.increment_amount
...
>>>i = Incrementor(1)
>>>val = i.increment(3)
>>>print val
4

Once you understand this, the use of the __call__ method becomes
apparent:
>>>class Incrementer:
>>>	def __init__(self, increment_amount):
>>>		self.increment_amount = increment_amount
>>>	def __call__(self, value):
>>>		return value + self.increment_amount
...
>>>i = Incrementor(1)
>>>val = i(3)
>>>print val
4


Akira Kiyomiya wrote:
> 
> Hi,  Could you explain this in dummy's language?
> 
> This function prints out '4' and I have a feeling that x=1 and n=3, so
> add1(3) prints '4'.
> 
> However, I have a difficlut time trying to see how these two arguments
> assigned to both x (especially x) and n.
> 
> Thanks
> 
> Akira
> 
> # Return a function that returns its argument incremented by 'n'
> def make_incrementer(n):
>     def increment(x, n=n):
>         return x+n
>     return increment
> 
> add1 = make_incrementer(1)
> print add1(3)  # This prints '4'
> 
> --
> http://www.python.org/mailman/listinfo/python-list

-- 
Sean Blakey
FreeInternet.com
sblakey at freei.com
(253)796-6500x1025




More information about the Python-list mailing list