“导入X”之间的差异和“来自X import *”?
在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?
在导入x
之后,你可以参考 x
中的内容,如 x.something
。在x import * 之后的之后,您可以直接引用
的 x
中的内容,就像
。由于第二种形式将名称直接导入本地名称空间,因此如果从多个模块导入内容,则会产生冲突的可能性。因此,不鼓励来自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.
您也可以从x执行导入一些
,它只将某些东西
导入本地命名空间,而不是 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.