Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可能从另一个文件(python)导入函数会改变代码的结果?_Python_Import - Fatal编程技术网

是否可能从另一个文件(python)导入函数会改变代码的结果?

是否可能从另一个文件(python)导入函数会改变代码的结果?,python,import,Python,Import,我从另一个python文件导入了一个函数,它使我的代码运行了2次 代码是这样的 n = int(input("\nCombien des disques? \nNombres des disques: ")) display = init(n) print("\nYour playground looks like this: \n", display) 在几行之后: from Partie_C import boucle_jeu 此导入将使此代码再次运行: n = int(input("\

我从另一个python文件导入了一个函数,它使我的代码运行了2次

代码是这样的

n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)
在几行之后:

from Partie_C import boucle_jeu
此导入将使此代码再次运行:

n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)

所以你明白。。。如果没有它,它只要求“n”打印消息并完成(仅一次)

您描述的唯一合理的方式是如果
Partie\u C
正在导入包含
n=…
的文件,从而导致循环导入

循环导入将导致代码运行两次,因为导入将导致对导入的文件进行解释。如果导入
Partie\u C
,它将运行。如果
Partie\u C
然后导入此代码,则此代码将作为导入的结果运行

# Code runs here obviously
n = int(input("\nCombien des disques? \nNombres des disques: "))  
display = init(n)
print("\nYour playground looks like this: \n", display)

 # Indirectly imports this file, causing the whole file to be interpreted again, running the above code again
from Partie_C import boucle_jeu

要解决此问题,请将代码放在函数中,而不是放在顶层,或者使用导入保护(
if\uuuuu name\uuuuu==“\uuuuu main\uuuu”
)。或者更好的是,不要循环进口。循环进口通常被认为是一种代码气味。重新排列代码,这样就不会有两个文件相互导入

你对如何包括进口保护有什么想法吗<代码>如果uuu name uuuu==“uuuu main uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu无法由其他文件导入或由其他文件使用functions@AugustinComan如果需要它在导入时可用,请将该代码放入函数中,然后从该函数返回
n
(和
display
)。然后调用需要该数据的函数。无论如何,在加载文件时运行
input
是一种糟糕的做法。实际上,所有的代码都应该隐藏在函数中,除了乱搞的时候。