![](/img/trans.png)
[英]What is the proper way to pass an empty list in python from the main function?
[英]Python 3.9, a proper way to return from a function back to main menu
我是编程和 Stackoverflow 的新手。 我目前正在研究文件处理和类。 该程序正在运行,但我的问题是这部分代码是否可以接受? list_of_objects 是一个带有“[]”的列表,其中包含 class 对象。
def menu_choice_function(list_of_objects):
while True:
menu()
choice = input("Choice: ")
if choice == "1":
print("Create a packing list")
list_of_objects = create_packing_list(list_of_objects)
elif choice == "2":
print("Show the packing list content")
show_packing_list_content(list_of_objects)
elif choice == "3":
print("Append or delete items in the packing list")
list_of_objects = app_del_items(list_of_objects)
elif choice == "4":
print("Show all packing lists")
show_all_packing_list(list_of_objects)
elif choice == "5":
print("Edit the packing list name or date")
list_of_objects = edit_name_date(list_of_objects)
elif choice == "6":
print("Remove a packing list")
list_of_objects = remove_packing_list(list_of_objects)
elif choice == "7":
print("Add reminder or remove reminder for the packing list")
list_of_objects = add_remove_reminder(list_of_objects)
elif choice == "8":
return list_of_objects
else:
print("Please enter a choice.")
如果可以接受,我的意思是您可以看到一些函数返回一个修改后的列表,但它们都与参数变量具有相同的名称。 我这样做是因为我认为您可以修改列表变量。 但我想知道这种方法是否会带来一些后果。 到目前为止它正在工作,因为到目前为止程序中没有错误或奇怪的行为。 对不起,我的英语不好。 我希望你明白我想问什么。
假设,为了这个例子,你的函数被命名为 func1-7 并且每个函数都有一个列表,它用于参考或修改它。 请记住,列表是通过引用传递的,因此您可以在函数中更改它们。
此外,您可以使整个菜单系统参数驱动。 这使得添加或删除功能变得更加容易。
考虑一下:
def func1(loo):
print('Executing func1')
def func2(loo):
print('Executing func2')
def func3(loo):
print('Executing func3')
def func4(loo):
print('Executing func4')
def func5(loo):
print('Executing func5')
def func6(loo):
print('Executing func6')
def func7(loo):
print('Executing func7')
PARAMS = {1: ['Create a packing list', func1],
2: ['Show the packing list content', func2],
3: ['Append or delete items in the packing list', func3],
4: ['Show all packing lists', func4],
5: ['Edit the packing list name or date', func5],
6: ['Remove a packing list', func6],
7: ['Add reminder or remove reminder for the packing list', func7]
}
def menu(list_of_objects):
while True:
for k, v in PARAMS.items():
print(f'{k}: {v[0]}')
try:
if (i := int(input('Please select an option from the menu or zero to end: '))) == 0:
break
if (a := PARAMS.get(i, None)):
a[1](list_of_objects)
except ValueError:
pass
menu([])
您可以使用关键字global访问和修改 function 中的列表,因此您不必将其传递给您调用的每个 function。 查看本教程以了解如何使用它。
至于它是否可以接受,我会说具有相同名称的参数和变量会降低代码的可读性,所以我会更改命名。
只要它有效,它就没有错,但为了可读性和简单性以及我对您的代码的看法:
如果您只想初始化或填充列表,则不需要将其传递给 function,除非您需要其中的数据。
上面的 if 链很好,不要打印带有魔法值的消息,而是将您的消息保存在变量中并在最后打印。
这些是我能告诉你的唯一事情,如果有其他事情只是评论它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.