【发布时间】:2019-02-05 22:59:30
【问题描述】:
我有一个类,它有几个方法可以从用户输入中分配属性,还有三个方法可以使用输入添加、删除或更新嵌套字典。 我想添加一个 main_menu 函数,以便用户可以访问添加、删除和更新方法,然后选择继续添加/删除/更新字典,或者返回主菜单。
当我尝试创建一个 main_menu 函数时,我收到 NameError: name 'command' is not defined。如果 main_menu 不是函数,则程序将按预期循环,但是一旦我尝试将其转换为函数,就会出现错误。我尝试了不同级别的缩进,但我是 Python 新手,不知道还能尝试什么。
class MyClass:
def __init__(self):
self.x = 0
self.y = 0
self.z = 0
def get_x(self):
#code to get x from user input
def get_y(self):
#code to get y from user
def get_z(self):
#code to get z from user
def add_info(self):
store_info = {}
id = 0
while command = '1':
new_info = {}
new_id = len(store_info) + 1
store_info[new_id] = new_info
x = h.get_x()
new_info['x'] = x
y = h.get_y()
new_info['y'] = y
z = h.get_z()
new_info['z'] = z
print('Your info has been updated.\n', store_info)
choice = input('To add more info, type 1. To return to the main menu, type 2')
if choice == '1':
continue
elif choice == '2':
main_menu()
else:
print('The End')
break
def delete_info(self):
#code to delete, with an option at the end to return to main_menu
def update_info(self):
#code to update, with option for main_menu
def main_menu():
main_menu_option = """Type 1 to add.
Type 2 to delete.
Type 3 to update.
Type any other key to quit.\n"""
h = MyClass()
command = input(main_menu_option)
if command == '1':
h.add_info()
elif command == '2':
h.delete_info()
elif command == '3':
h.update_info()
else:
print('Good bye.')
main_menu()
当我运行程序时,我得到主菜单并输入 1,但随后收到 NameError for command。 在我尝试将 main_menu 设为函数之前,我可以访问 add 方法将信息添加到嵌套字典中。
【问题讨论】:
-
能否在您的问题中包含堆栈跟踪信息?它有助于我们更好地理解问题。
-
对不起,我是新手。这和回溯一样吗?
-
不用担心,和回溯一样。不过现在不用担心,我已经为您的问题添加了答案:)
-
我确实想更好地发布问题,所以我需要包含的不仅仅是 NameError?类似“在 add_info while command == '1': NameError: name 'command' is not defined.
-
知道了,我会在以后的问题中记住这一点。感谢您的意见。
标签: python-3.x function class