[Tutor] map() and lambda to change class instance attribute

Bernard Lebel 3dbernard at gmail.com
Wed May 11 20:39:15 CEST 2005


Hi Danny,

Thanks for the answer.

I have to confess that I already use map(), or should I say abuse, for
this, although it is the first time I consider using lambdas. Up until
now I always used map() to perform a looped call on a function that
would change the attribute value, as shown in Mark Lutz & David
Ascher's Learning Python:

# Perform attribute value change on a single instance
def iterateInstances( oInstance ):
     oInstance.value = myValue

# Loop over list of instances
map( iterateInstances, aListOfInstances )

However I was looking into lambdas in hope to eliminate the need to
define a function.

Cheers



On 5/11/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> 
> 
> On Wed, 11 May 2005, Bernard Lebel wrote:
> 
> > Let say I have several class instances in a list, and these class
> > instances have an attribute named "value", whose value is an integer.
> >
> > I would like to know if it is possible to loop over the list of
> > instances to change their "value" attribute, using a map( ( lambda:...),
> > ... ) type of loop.
> 
> Hi Bernard,
> 
> Hmmm... then map() is probably not what you want.  map() is meant to
> transform a list of things into another list of things, but isn't really
> meant to mutate its input.
> 
> It is possible to abuse map() to do what you're trying to do, using the
> setattr() function:
> 
> ###### Pseudocode
> map(lambda instance: setattr(instance, 'value', 42))
> ######
> 
> but this is definitely language abuse.  *grin*
> 
> map() is not intended to be run just to affect changing assignments on its
> input.  It'll probably be clearest in Python just to write out the loop
> explicitely.
> 
> Best of wishes to you!
> 
>


More information about the Tutor mailing list