Function lookup using a directory.

andy.pevy at nokia.com andy.pevy at nokia.com
Tue Jun 19 08:56:55 EDT 2001


Hi again guys

	Thanks for all the very helpful suggestions.  I have managed
to make it do what I want now.

The killer was the actual code to call the looked up class :- 

    try:
        h = command_table[command[0]]
    except:
        print command[0]+' not found'
    
    h.run(h(),command)

It seems that you have to manually pass in the 'self' parameter
when calling functions this way.

Anyway, I am sure I will be back.

Thanks

Andy Pevy 

andy.pevy at nokia.com wrote:
> Hi Guys

> 	I am having trouble with the directory data type. What I want to
> do is to set up a directory that I can use to parse a command entered by 
> the user, and have a directory return the name of a class to handle the 
> command.  Like this :-


> command_table = {'0':    'Help0',
>             '1':    'Help1',
>             '2':    'Help2',
>             '3':    'Help3' }

> class Help0:
>             
>     def run(self,which):
>         if len(which) == 1:
>             print 'Help no args'
>         else:
>             print 'Help args' 

> class Help1:

>     def run(self,which):
>         if len(which) == 1:
>             print 'Help1 no args'
>         else:
>             print 'Help1 args'

> class Help2: 

>     def run(self,which):
>         if len(which) == 1:
>             print 'Help2 no args'
>         else:
>             print 'Help2 args'

> class Help3: 

>     def run(self,which):
>         if len(which) == 1:
>             print 'Help3 no args'
>         else:
>             print 'Help3 args'


> if __name__ == '__main__':

>     command = user_input()

>     try:
>         h = command_table[command[0]]
>     except:
>         print command[0]+' not found'

>     h.run()	# Call the run method of the selected class.



> So, a couple of questions please.....

> Can I do this, I.E. have a class as a value in a dictionary
> and if so, what would the correct declaration be.

> Thanks.


> Andy Pevy
> A Very Beginner Pythoneer.

> -- 

> We were always told that a million monkeys typing for a million years
> would eventually produce the works of Shakespeare. Now, thanks to the
> Internet, we know this is not true.

-- 

We were always told that a million monkeys typing for a million years
would eventually produce the works of Shakespeare. Now, thanks to the
Internet, we know this is not true.



More information about the Python-list mailing list