【问题标题】:Best way to import modules Python [duplicate]导入模块Python的最佳方法[重复]
【发布时间】:2018-04-17 04:57:08
【问题描述】:

你们可以这样import

 from .models import *

或者像这样

from .models import Student

【问题讨论】:

  • 1 或 2 可能会乱扔命名空间。根据情况使用 3 或 4。 4 如果您想将导入的对象保留在模块命名空间内以获得更好的可读性。 3 适用于特定类名(如模型)。 3 和 4 的例子对于各自的情况都很好

标签: python coding-style python-import


【解决方案1】:

来自 PEP8:Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).

通常您只想导入您需要的内容,并确保导入是明确的(例如,列表中的第三个选项,但有时也包括第四个选项)。

【讨论】:

    【解决方案2】:

    一般而言,这取决于您要做什么以及您的编程风格。尽管它们都可能有效,但我建议坚持使用更明确的样式,例如您列出的 (3) 和 (4)。

    使用 * 一次导入所有内容的问题是它们容易出现命名空间错误,并且不清楚您实际使用的是哪些模块。

    虽然看起来工作量更大,但如果您坚持只在需要时导入所需的内容,它会导致更好的程序更容易遵循。

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      相关资源
      最近更新 更多