generating method names 'dynamically'
Steve Holden
steve at holdenweb.com
Fri Jan 27 08:17:59 EST 2006
Daniel Nogradi wrote:
>>Here you go:
>>
>> >>> database = {
>> ... "Alice": 24,
>> ... "Bob":25}
>> ...
>> >>> class Lookup(object):
>> ... def __catcher(self, name):
>> ... try:
>> ... print "Hello my name is %s and I'm %s" % (name,
>>database[name])
>> ... except KeyError:
>> ... print "There was an error"
>> ... def __getattr__(self, attr):
>> ... return lambda:self.__catcher(attr)
>> ...
>> >>> inst = Lookup()
>> >>> inst.Alice()
>> Hello my name is Alice and I'm 24
>> >>> inst.Bob()
>> Hello my name is Bob and I'm 25
>> >>> inst.John()
>> There was an error
>> >>>
>>
>
>
> Great, that was exactly what I was asking, thank you very much.
While I hesitate to rain on this little parade, I would caution you
against adopting this solution as a generic programming tool. If people
just need to interact with the database in an ad hoc way then this will
let them do it, but it's a very poor recipe for general database search,
since the content of your database determines the text of your program.
You might well find, on thinking about it a little more, that it mught
be more straightforward to adopt a system more like this:
name = raw_input("Who do you want to know today: ")
inst = Lookup(name)
inst.show()
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list