generating method names 'dynamically'

Daniel Nogradi nogradi at gmail.com
Thu Jan 26 20:32:07 EST 2006


> 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.



More information about the Python-list mailing list