在Python3中,`import`是否可以传递? [英] In Python3, does `import` work transitively?
问题描述
在Python3中, import
是否可传递?
In Python3, does import
work transitively?
例如,如果模块包含导入A
, A
的模块包含导入B
,然后执行模块导入 B
间接?
For example, if a module contains import A
, and the module for A
contains import B
, then does the module import B
indirectly?
与其他语言相比:
-
在Java中,有人说
import
不能传递,请参阅 https://stackoverflow.com/a/46677664 。
In Java, some said that
import
doesn't work transitively, see https://stackoverflow.com/a/46677664.
在C中, include
确实可以传递。例如,如果文件包含 #includeAh
,并且 Ah
包含 #include Bh
,然后该文件间接包含 Bh
。
in C, include
does work transitively. For example, if a file contains #include "A.h"
, and A.h
contains #include "B.h"
, then the file also includes B.h
indirectly.
Python的导入
,Java的导入和C的
包含`挂钩有差异吗?
How do Python's import
, Java's import, and C's
include` work under the hook to have differences?
谢谢。
推荐答案
当你'将模块导入命名空间后,Python会创建一个模块命名空间。这是递归的;当您导入 A
时,它将导入 B
,如果失败,您将收到错误。否则可以通过 AB
When you're importing a module to your namespace, Python creates a module namespace. This goes recursively; when you import A
, it will import B
and if it fails you'll get an error. Otherwise it will be accessible through A.B
# temp.py
def func_in_b():
print 'this is B'
# temp2.py
import temp
def func_in_a():
print 'this is A'
>>> import temp2
>>> temp2.func_in_a()
this is A
>>> temp2.temp.func_in_b()
this is B
这篇关于在Python3中,`import`是否可以传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!