接受命令并调用方法

2024-09-28 01:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含不同方法的类。你知道吗

现在我想让main()充当REPL。我有不同的命令,每个都引用不同的方法。(例如command1(callmethod1))

我想将提示打印为>;>; 一次接受一个命令,然后调用

我该怎么做?你知道吗

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

    def main():

顺便说一下,我使用的是python3.5


Tags: 方法命令gtselfobjectinitmaindef
1条回答
网友
1楼 · 发布于 2024-09-28 01:32:49

您可以使用getattr()函数按名称获取属性,然后只调用生成的方法对象:

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)())

如果方法名与命令不同,则需要某种方法来翻译(然后就不需要使用getattr):

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

相关问题 更多 >

    热门问题