python - 在 cmd 模块 python 中调用菜单

标签 python python-2.7 command-line

我正在使用 python 的 cmd 模块制作一个命令行程序。在此程序中,我使用数字来确定用户想要使用什么功能。我对功能 6 遇到以下问题,它只是再次打印出功能,但我想调用 MainMenu 类,这样我就不必使用:

def do_6(self, line):
        print ("   M A I N - M E N U")
        print ("1. Feature one")
        print ("2. Feature two")
        print ("3. Feature three")
        print ("4. Feature four")
        print ("5. Feature five")
        print ("6. Print options")
        print ("7. Exit ")
        print (30 * '-')

这只是重复 MainMenu 类中的内容,但如果您想更改 MainMenu,则有点草率。您还被迫更改功能 6。

主菜单类:

class MainMenu(cmd.Cmd):
    print ("   M A I N - M E N U")
    print ("1. Feature one")
    print ("2. Feature two")
    print ("3. Feature three")
    print ("4. Feature four")
    print ("5. Feature five")
    print ("6. Print options")
    print ("7. Exit ")
    print (30 * '-')

我尝试这样做:

def do_6(self, line):
        MainMenu()

def do_6(self, line):
        MainMenu

但这没有效果,我如何正确调用我的 MainMenu 类?我的第二个问题是:假设我想在每次功能结束或完成时调用 MainMenu 类,我该怎么做?

最佳答案

class MainMenu(cmd.Cmd):

    def __init__(self):
        """ Class constructor """

        print ("   M A I N - M E N U")
        print ("1. Feature one")
        print ("2. Feature two")
        print ("3. Feature three")
        print ("4. Feature four")
        print ("5. Feature five")
        print ("6. Print options")
        print ("7. Exit ")
        print (30 * '-')

您需要了解类(class)是如何运作的。类具有成员、方法和许多其他功能。与所有语言一样,您需要定义此字段。例如,这是一个带有构造函数、字段和方法的方法:

class Example:

    field = "foo"

    def __init__(self, ivar_value):
        self.instance_var = ivar_value

    def print_me(self):
        print("Field : ", self.field)
        print("Var   : ", self.instance_var)

类只定义一次。当您尝试按照自己的方式运行 MainMenu() 时,它只能运行一次,因为第二次时,MainMenu 类已经被定义了。

关于python - 在 cmd 模块 python 中调用菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31748200/

相关文章:

python-2.7 - 使用 opencv 从 SIFT 生成以百分比表示的相似度分数

java - 在终端上使用 -classpath 不起作用

python - 如何使用 python、Flask 和命令行传递 URL 参数

bash - 脚本中的 source .bashrc 不起作用

python - 如何缓存和迭代未知大小的数据集?

Python 无法从 bazel git_repository() 依赖项导入包

python - 从 Pandas 的日期时间变量中删除时间?

python - 在 Python 中使用 PyQt 将数据从 sqlite 数据库插入到 QTableWidget

python - 在 Python 中比较字节

python - 如何在 lambda 函数中执行赋值