[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: question

Tim Chase

1/22/2008 8:32:00 PM

> def albumInfo(theBand):
> def Rush():
> return ['Rush', 'Fly By Night', 'Caress of Steel',
'2112', 'A Farewell to Kings', 'Hemispheres']
>
> def Enchant():
> return ['A Blueprint of the World', 'Wounded', 'Time Lost']
>
> The only problem with the code above though is that I
> don't know how to call it, especially since if the user is
> entering a string, how would I convert that string into a
> function name? For example, if the user entered 'Rush',
> how would I call the appropriate function -->
> albumInfo(Rush()) >

It looks like you're reaching for a dictionary idiom:

album_info = {
'Rush': [
'Rush',
'Fly By Night',
'Caress of Steel',
'2112',
'A Farewell to Kings',
'Hemispheres',
],
'Enchant': [
'A Blueprint of the World',
'Wounded',
'Time Lost',
],
}

You can then reference the bits:

who = "Rush" #get this from the user?
print "Albums by %s" % who
for album_name in album_info[who]:
print ' *', album_name

This is much more flexible when it comes to adding groups
and albums because you can load the contents of album_info
dynamically from your favorite source (a file, DB, or teh
intarweb) rather than editing & restarting your app every time.

-tkc

PS: to answer your original question, you can use the getattr()
function, such as

results = getattr(albumInfo, who)()

but that's an ugly solution for the example you gave.