gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:44 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com