joe
joe

Reputation: 161

accept commands and call the methods

I have a class which contain different methods.

now I want my main() acts as a REPL. I have different commands each refers to a different method. (eg. command1(call method1) )

I want to print a prompt as >>> and accept one command at a time then call the method

how can I do this?

    class supermarket(object):
            def __init__(self):
                    pass
            def method1(self):
                    pass
            def method2(self):
                    pass
            ...

    def main():

by the way, i am using python 3.5

Upvotes: 2

Views: 53

Answers (1)

thebjorn
thebjorn

Reputation: 27351

You can use the getattr() function to fetch attributes by name, then just call the resulting method object:

def main():
    s = supermarket()
    while 1:
        cmd = input('>>> ')  # or raw_input('>>> ') if using Python < 3
        if cmd in ('q', 'quit'):
            break
        print(getattr(s, cmd)())

if the method names are different from the commands you'll need some way to translate (and then there is no need to use getattr):

def main():
    s = supermarket()
    while 1:
        cmd = input('>>> ')
        if cmd in ('q', 'quit'):
            break
        print({
            'command1': s.method1,
            'command2': s.method2,
            # ...
        }[cmd]())

Upvotes: 3

Related Questions