使用“导入模块"还是“从模块导入"? [英] Use 'import module' or 'from module import'?
问题描述
我试图找到一份关于最好使用 import module
还是 from module import
的综合指南.我刚刚开始使用 Python,我正在努力从最佳实践开始.
I've tried to find a comprehensive guide on whether it is best to use import module
or from module import
. I've just started with Python and I'm trying to start off with best practices in mind.
基本上,我希望是否有人可以分享他们的经验、其他开发者的偏好以及避免任何陷阱的最佳方法是什么?
Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?
推荐答案
import module
和 from module import foo
的区别主要是主观的.选择您最喜欢的一种,并在使用时保持一致.以下几点可以帮助您做出决定.
The difference between import module
and from module import foo
is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.
导入模块
- 优点:
- 减少对
import
语句的维护.不需要添加任何额外的导入来开始使用模块中的另一个项目
- Pros:
- Less maintenance of your
import
statements. Don't need to add any additional imports to start using another item from the module
- 在你的代码中输入
module.foo
可能是乏味和多余的(可以通过使用import module as mo
然后输入mo.foo代码>)
- Typing
module.foo
in your code can be tedious and redundant (tedium can be minimized by usingimport module as mo
then typingmo.foo
)
from module import foo
- 优点:
- 使用
foo
减少输入 - 更多地控制可以访问模块的哪些项目
- 要使用模块中的新项目,您必须更新
import
语句 - 你失去了关于
foo
的上下文.例如,与math.ceil()
相比,
ceil()
的作用不太清楚- To use a new item from the module you have to update your
import
statement - You lose context about
foo
. For example, it's less clear whatceil()
does compared tomath.ceil()
任一种方法都可以,但不要使用
from module import *
.Either method is acceptable, but don't use
from module import *
.对于任何合理的大型代码集,如果您
import *
,您很可能会将其固定到模块中,无法删除.这是因为很难确定代码中使用的哪些项来自模块",因此很容易达到您认为不再使用import
但它是极难确定.For any reasonable large set of code, if you
import *
you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use theimport
any more but it's extremely difficult to be sure.这篇关于使用“导入模块"还是“从模块导入"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 使用
- Less maintenance of your
- 减少对