问题描述
在 Python 中,我不太清楚以下两行代码之间的区别:
In Python, I'm not really clear on the difference between the following two lines of code:
import X
或
from X import *
他们不是都只是从模块 X 中导入所有内容吗?有什么区别?
Don't they both just import everything from the module X? What's the difference?
推荐答案
import x
后,可以引用x
中的东西,如x.something代码>.在
from x import *
之后,你可以像something
一样直接引用x
中的东西.因为第二种形式将名称直接导入到本地命名空间中,所以如果您从许多模块导入内容,则可能会产生冲突.因此,不鼓励使用 from x import *
.
After import x
, you can refer to things in x
like x.something
. After from x import *
, you can refer to things in x
directly just as something
. Because the second form imports the names directly into the local namespace, it creates the potential for conflicts if you import things from many modules. Therefore, the from x import *
is discouraged.
您也可以执行 from x import something
,它只将 something
导入本地命名空间,而不是 x
中的所有内容.这更好,因为如果您列出您导入的名称,您就可以确切地知道您要导入的内容,并且更容易避免名称冲突.
You can also do from x import something
, which imports just the something
into the local namespace, not everything in x
. This is better because if you list the names you import, you know exactly what you are importing and it's easier to avoid name conflicts.
这篇关于“import X"与“import X"的区别和“从 X 导入 *"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!