多次导入同一python模块 [英] Import same python module more than once
问题描述
由于某种特定的按键操作,我试图找到一种不止一次导入同一模块的方法.
I am trying to find a way of importing the same module more than once due to a certain key press....
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
import forest_level
if event.key == pygame.K_2:
import sea_level
if event.key == pygame.K_3:
import desert_level
if event.key == pygame.K_4:
import underwater_level
if event.key == pygame.K_5:
import space_level
假设我在森林里,然后去了海平面,我将如何回到森林里?
say if I were in the forest level and went to the sea level, how would I get back to forest level?
GAME CODE
推荐答案
您不能.
由于您还没有提供简短,自包含,正确(编译),示例.
您可能有几个看起来像这样的模块:
You probably have several modules that look like:
# foo_level.py
print "foo"
以及一个主要模块:
# main.py
while True:
key = raw_input()
if key == "foo":
import foo_level
# and so on.
import
语句旨在将代码引入作用域,而不是实际执行任何代码.
the import
statement is designed for bringing code into scope, not for actually executing any code.
将要运行的所有代码多次放入一个函数中:
Put all of the code you want to run multiple times in a function:
# foo_level.py
def do_stuff():
print "foo"
,而是在开始时一次导入所有模块,然后在循环内调用新函数:
and instead, import all modules once, at the beginning and call the new functions inside the loop:
# main.py
import foo_level
while True:
key = raw_input()
if key == "foo":
foo_level.do_stuff()
# and so on.
这篇关于多次导入同一python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!