list comprehensions to effect visitors
Bruce Eckel
Bruce at EckelObjects.com
Thu Dec 6 21:49:35 EST 2001
>I thought "list comprehensions" was a typo
>(should've been "...incomprehensions") until I discovered that
>the leftmost element was evaluated anew for each element.
>Suddenly it became easy to invoke the same method on a whole
>collection of objects, without lambda:
>
> [foo.asTabSeparatedValue() for foo in selection]
Whoa! (slaps forehead). I've wanted to do this very thing a bunch
of times. And the gods of Python clearly anticipated my needs.
>With list comprehensions many applications of the visitor design
>pattern can be reduced to a single statement.
Based on this, I fooled around with my visitor example until I got
it to work in some fashion with list comprehensions. It cleaned up
nicely. Note the last line, in particular:
# Using list comprehensions to effect visitors.
class Flower:
def pollinate(self, pollinator):
print `self`, "pollinated by", `pollinator`
def eat(self, predator):
print `self`, "eaten by", `predator`
def __repr__(self):
return self.__class__.__name__
class Gladiolus(Flower): pass
class Runuculus(Flower): pass
class Chrysanthemum(Flower): pass
class Bug:
def __repr__(self):
return self.__class__.__name__
class Pollinator(Bug): pass
class Predator(Bug): pass
class Bee(Pollinator): pass
class Fly(Pollinator): pass
class Worm(Predator): pass
import random
rgen = random.Random()
flwrs = [Gladiolus(),Runuculus(),Chrysanthemum()]
flowers = [rgen.choice(flwrs) for i in range(10)]
bee = Bee()
fly = Fly()
worm = Worm()
[(f.pollinate(bee), f.pollinate(fly), f.eat(worm)) for f in
flowers]
At this point I'm trying to figure out
(A) what does multiple dispatching mean in Python?
(B) does Python already, in effect, *do* multiple dispatching, or
perhaps just remove the need for it?
>Sorry for the spewage. It's just that I see many posts from you
>today, and am assuming you're working on "Thinking in Python"
>(or something like it) and am hoping that you plan to cover
>the foregoing therein. If you do, I'll have an *intelligible*
>explanation of list comprehensions :)
I am in fact feverishly translating "Thinking in Patterns" into
"Thinking in Python" to prepare for my tutorial at the Python
conference, which is due monday. I was certain it would be an
enormous job as it was with C++ and Java to write these examples,
but as usual Python changes everything, and I might even hit the
deadline.
Most current information can be found at:
http://www.mindview.net/Etc/notes.html
===================
Bruce Eckel http://www.BruceEckel.com
Contains free electronic books: "Thinking in Java 2e" & "Thinking
in C++ 2e"
Please subscribe to my free newsletter -- just send any email to:
join-eckel-oo-programming at earth.lyris.net
My schedule can be found at:
http://www.mindview.net/Calendar
===================
More information about the Python-list
mailing list