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

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed May 11 20:33:12 CEST 2005



---------- Forwarded message ----------
Date: Wed, 11 May 2005 14:29:58 -0400
From: Bernard Lebel <3dbernard at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] map() and lambda to change class instance attribute

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
Bernard


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