【发布时间】:2023-03-19 15:25:01
【问题描述】:
def add():
import add_coffee_record
import imp
imp.reload(add_coffee_record)
def show():
import show_coffee_records
import imp
imp.reload(show_coffee_records)
def search():
import search_coffee_records
import imp
imp.reload(search_coffee_records)
def modify():
import modify_coffee_records
import imp
imp.reload(modify_coffee_records)
def delete():
import delete_coffee_record
import imp
imp.reload(delete_coffee_record)
def main():
num=input('\nEnter the number on the menu: ')
while num != '6':
if num == '1':
print()
add()
if num == '2':
print()
show()
if num == '3':
print()
search()
if num == '4':
print()
modify()
if num == '5':
print()
delete()
num=input('\nEnter the number on the menu: ')
main()
我的输出如下所示:
Enter the number on the menu: 2
Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0
Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0
Enter the number on the menu: 2
Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0
Enter the number on the menu: 2
Description: Thanksgiving Blend
Quantity: 300.0
Description: Christmas Blend
Quantity: 100.0
如果第一个输出不会复制自己,我会喜欢它。有没有办法构建程序,在第一个实例上只使用“导入”,而在后续实例上使用“重新加载”?注意:我不能复制粘贴程序文件而不是导入。我需要使用导入。谢谢。
【问题讨论】:
-
或许
try: imp.reload(module); except ImportError: import module? -
我认为您对
import的使用感到困惑。它的目的不是运行某些代码,而是使模块在当前上下文中可用。尽管它确实第一次运行模块来执行此操作,但您不应将其用于初始设置之外的任何其他操作。 — 在这里,您应该在顶部执行所有导入,并让它们定义您之后调用的函数。 -
注意:
imp在 Python 3 中已被importlib取代,imp基本上已被弃用。
标签: python function python-3.x import while-loop