代码之家  ›  专栏  ›  技术社区  ›  Jamil Noyda

导入模块的最佳方式Python[复制]

  •  -2
  • Jamil Noyda  · 技术社区  · 7 年前

    你们可以 import 像这样

     from .models import *
    

    或者像这样

    from .models import Student
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   ZaxR    7 年前

    来自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
  •  1
  •   fhorrobin    7 年前

    一般来说,这取决于您正在尝试做什么以及您的编程风格。虽然它们都可能有效,但我建议坚持使用更明确的样式,如您列出的(3)和(4)。

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

    虽然看起来需要做更多的工作,但如果你坚持只导入你需要的东西,它将导致更好的程序,更容易遵循。