generating method names 'dynamically'
Michael Spencer
mahs at telcopartners.com
Thu Jan 26 20:22:28 EST 2006
Daniel Nogradi wrote:
...
> --------- database content -----------
>
> Alice 25
> Bob 24
>
> --------- program1.py -------------
>
> class klass:
...
>
> inst = klass()
>
> --------- program2.py -----------
>
> import program1
>
> # The code in klass above should be such that the following
> # line should print 'Hello my name is Bob and I'm 24.'
> program1.inst.Bob()
>
> # The code in klass above should be such that the following
> # line should print 'Hello my name is Alice and I'm 25.'
> program1.inst.Alice()
>
> # The code in klass above should be such that the following
> # line should print 'There was an error.'
> program1.inst.John()
>
...
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
>>>
HTH, Michael
More information about the Python-list
mailing list