[英]NameError when importing function from another script?
I am having difficulty importing a function from another script. 我很难从另一个脚本导入函数。 Both of the scripts below are in the same directory. 以下两个脚本位于同一目录中。 Why can't the function from another script handle an object with the same name ( arr
)? 为什么另一个脚本中的函数不能处理具有相同名称( arr
)的对象?
evens.py 偶数
def find_evens():
return [x for x in arr if x % 2 == 0]
if __name__ == '__main__':
arr = list(range(11))
print(find_evens())
import_evens.py import_evens.py
from evens import find_evens
if __name__ == '__main__':
arr = list(range(11))
print(find_evens())
Traceback 追溯
Traceback (most recent call last):
File "C:\Users\user\Desktop\import_evens.py", line 7, in <module>
find_evens()
File "C:\Users\user\Desktop\evens.py", line 2, in find_evens
return [x for x in arr if x % 2 == 0]
NameError: name 'arr' is not defined
Modules in python have separate namespaces. python中的模块具有单独的命名空间。 The qualified names evens.arr
and import_evens.arr
are separate entities. 合格名称evens.arr
和import_evens.arr
是单独的实体。 In each module, using just the name arr
refers to the one local to it, so arr
in import_evens
is actually import_evens.arr
. 在每个模块中,仅使用名称arr
指向该模块的本地名称,因此import_evens
arr
实际上是import_evens.arr
。
Since you are defining arr
inside of if __name__ ...
, the name arr
is only the defined in the executed module. 由于您要在if __name__ ...
内部定义arr
,因此名称arr
仅是在执行的模块中定义的。 The name evens.arr
is never defined. 从未定义过evens.arr
名称。
Further, there is no notion of truly global names. 此外,没有真正的全球名称的概念。 A name can be global to a module, so all entities inside it can use it. 名称可以是模块的全局名称,因此名称中的所有实体都可以使用它。 Any other module still has to address it as a_module.global_variables_name
. 其他任何模块仍必须将其寻址为a_module.global_variables_name
。 It can also be imported as from a_module import global_variables_name
, but this is just sugar for importing it and binding it to a new local name. 也可以from a_module import global_variables_name
,但这只是导入它并将其绑定到新的本地名称的糖。
# same as `from a_module import global_variables_name`
import a_module
global_variables_name = a_module.global_variables_name
What you have shown is best done via parameters to the function: 您所显示的内容最好通过函数的参数来完成:
# evens.py
def find_evens(arr):
return [x for x in arr if x % 2 == 0]
# import_evens.py
if __name__ == '__main__':
arr = list(range(11))
print(find_evens(arr))
If you think it's better to have global variables for this but don't understand how a language uses global variables, it's better not to have global variables. 如果您认为最好使用全局变量,但又不了解语言如何使用全局变量,那么最好不要使用全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.