“导入X”之间的差异和“来自X import *”? [英] Difference between "import X" and "from X import *"?

查看:95
本文介绍了“导入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.

这篇关于“导入X”之间的差异和“来自X import *”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆