使用“导入模块"还是“从模块导入"? [英] Use 'import module' or 'from module import'?

查看:72
本文介绍了使用“导入模块"还是“从模块导入"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一份关于最好使用 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 modulefrom 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 using import module as mo then typing mo.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 what ceil() does compared to math.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 the import any more but it's extremely difficult to be sure.

        这篇关于使用“导入模块"还是“从模块导入"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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