> 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))
> ######


Hi Bernard,

Grrr... I did label that as Pseudocode, but that doesn't excuse me from
not actually trying to make that example work.  My apologies!  That code
above wont' work, just because I neglected to add the required 'list' that
we want to map across.

Let me try that again.

######
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...         self.age = 4
...     def sayHello(self):
...         print "Hi, my name is", self.name, "and I am", self.age
...
>>> people = map(Person, ["Danny", "Andy", "Belinda", "Jerry", "Wendy",
...                       "Tina"])
######

Here, the use of map() is legitimate: we're mapping a list of names into a
list of people.


If we wanted to now make a change across them, we could go obfuscated and
do another map():

######
>>> map(lambda p: setattr(p, 'age', 26), people)
[None, None, None, None, None, None]
>>> for p in people:
...     p.sayHello()
...
Hi, my name is Danny and I am 26
Hi, my name is Andy and I am 26
Hi, my name is Belinda and I am 26
Hi, my name is Jerry and I am 26
Hi, my name is Wendy and I am 26
Hi, my name is Tina and I am 26
######

But this is a case when using map() is probably not such a hot idea, just
because now we're using it for just the "side effects" of making changes.
We aren't even caring about the return value out of map().

And in that case, we may want to make such a change more visible, with an
explicit assignment:


######
>>> for p in people:
...     p.age = 17
...
>>> for p in people:
...     p.sayHello()
...
Hi, my name is Danny and I am 17
Hi, my name is Andy and I am 17
Hi, my name is Belinda and I am 17
Hi, my name is Jerry and I am 17
Hi, my name is Wendy and I am 17
Hi, my name is Tina and I am 17
######


Does this make sense?

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to