473,574 Members | 3,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

questions about functions inside a function

I want to create a list of function.

Here is my code:
In [9]: a = []

In [10]: for i in range(4):
....: b = lambda : i**2
....: a.append(b)
....:
....:

In [11]: for f in a:
....: f()
....:
....:
9
9
9
9

What I want is, the value of i should be bounded to the anonymous function.
And the output should like this:

for f in a:
print f()
0
1
4
9

How to achieve this?

Thanks a lot!
Jul 16 '07 #1
5 1218
"fd********@gma il.com" <fd********@gma il.comwrote:
What I want is, the value of i should be bounded to the anonymous
function. And the output should like this:

for f in a:
print f()
0
1
4
9

How to achieve this?
Use default arguments when defining your function: default arguments are
evaluated when the function is defined, bound arguments get the current
value of the variable at the point when it is referenced during the call.

Also, since you give your function a name anyway ('b') you might as well
use a named function as being clearer than using lambda:
>>a = []
for i in range(4):
def b(i=i):
return i**2
a.append(b)

>>for f in a:
f()
0
1
4
9
>>>
Jul 16 '07 #2
fd********@gmai l.com a écrit :
I want to create a list of function.

Here is my code:
In [9]: a = []

In [10]: for i in range(4):
....: b = lambda : i**2
....: a.append(b)
....:
....:

In [11]: for f in a:
....: f()
....:
....:
9
9
9
9

What I want is, the value of i should be bounded to the anonymous
function. And the output should like this:

for f in a:
print f()
0
1
4
9

How to achieve this?
>>a = [lambda i=i:i**2 for i in range(4)]
for f in a:
.... print f()
....
0
1
4
9
>>>
HTH
Jul 16 '07 #3
On Jul 16, 4:49 am, "fdu.xia...@gma il.com" <fdu.xia...@gma il.com>
wrote:

(snipped)
>
What I want is, the value of i should be bounded to the anonymous function.
And the output should like this:

for f in a:
print f()
0
1
4
9

How to achieve this?

Thanks a lot!


The functools module, in Python 2.5 allows:
>>import functools
square = lambda i: i ** 2
anon = [functools.parti al(square, i) for i in range(4)]
for f in anon:
.... print f()
....

--
Hope this helps,
Steven

Jul 16 '07 #4
fd********@gmai l.com wrote:
What I want is, the value of i should be bounded to the anonymous
function. And the output should like this:
....
How to achieve this?
This doesn't answer your question (others have), but another (perhaps
clearer) way to do such things is something like

class MyFunc(object):
"""A function object."""
def __init__(self, val):
self.val = val

def __call__(self):
"""Return value squared"""
return self.val**2

a = []
for i in range(4):
a.append(MyFunc (i))

for f in a:
f()
Jeremy

--
Jeremy Sanders
http://www.jeremysanders.net/
Jul 16 '07 #5
Jeremy Sanders a écrit :
fd********@gmai l.com wrote:

>>What I want is, the value of i should be bounded to the anonymous
function. And the output should like this:

...
>>How to achieve this?


This doesn't answer your question (others have), but another (perhaps
clearer) way to do such things is something like

class MyFunc(object):
"""A function object."""
def __init__(self, val):
self.val = val

def __call__(self):
"""Return value squared"""
return self.val**2

a = []
for i in range(4):
a.append(MyFunc (i))

for f in a:
f()
I wouldn't say it's "clearer" - at least in this concrete use case. And
it takes more than just defining the __call__ method to have a fully
function-like object (hint: try using a MyFunc instance as a method).
Jul 16 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2335
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and Methods Version: $Revision: 1.34 $ Last-Modified: $Date: 2004/09/03 09:32:50 $ Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
4
2131
by: Chuck Ritzke | last post by:
I keep asking myself this question as I write class modules. What's the best/smartest/most efficient way to send a large object back and forth to a class module? For example, say I have a data access module that creates a large disconnected dataset from a database. I want to pass that dataset back to the calling program. And then perhaps I...
15
1994
by: Pelle Beckman | last post by:
Hi all, I have a few newbie questions: In function declaration what does a 'const' mean inside the parameter list ? That it won't modify the value? void MemberFunction(const int x);
4
1824
by: Rhino | last post by:
I've been playing with Java UDFs for the last couple of days and I've got some questions about scratchpads. I'm running DB2 LUW V8 (FP8) on WinXP. Somewhere in the manuals, I found some remarks that said I could either manage my scratchpad with the getScratchpad() and setScratchpad() methods *OR* set up my own class variables to keep the...
15
1777
by: copx | last post by:
Q1: If an array is declared static in file A is it still valid to access it from file B? I mean if a function form file A which returns a pointer to a position inside of the array is called from file B can functions in file B read/write to the array using this pointer? I know that this works and doesn't produce a warning with every compiler...
9
1754
by: questions? | last post by:
if I use malloc() in a function to allocate a space for my array of structures. I didn't free() them anywhere in the program. I found that I can still use that space after I come back to main(). Am I supposed to use that space or it is temporary and will be removed soon afterwards? Thanks
39
2488
by: Digital Puer | last post by:
I'm not the world's greatest C++ programmer, so I had a hard time with these. Some help would be appreciated. 1. Comment on the declaration of function Bar() below: class Foo { static int Bar(int i) const; } (I said that since Bar is a static method, it can only access
6
2755
by: Venkatesh | last post by:
Hello All, I have couple of doubts regarding the concept of on-demand javascript loading using javascript code. I could see on the net different techniques for achieving this - techniques like: 1. document.write("<script src= language='JavaScript'></script>); 2. sc = document.createElement("<script>"); sc.setAttribute("src", ); and...
13
2078
by: John Dann | last post by:
A Python newbie, but some basic understanding of how classes, objects etc work in eg VB.Net. However, I'm struggling a little to translate this knowledge into the Python context. I'm trying to teach myself this aspect of Python by working up a trial project, part of which calls for pulling in data from a serial data connection at regular...
6
9600
KevinADC
by: KevinADC | last post by:
This snippet of code provides several examples of programming techniques that can be applied to most programs. using hashes to create unique results static variable recursive function serialization The code itself generates a list of strings comprised of random numbers. No number will be repeated within a string, and no string will...
0
7841
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7758
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8100
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8270
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7856
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3793
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1099
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.