导入模块的最佳方法Python [重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

你们可以像这样import

 from .models import *

或者像这样

from .models import Student
python coding-style python-import
2个回答
2
投票

来自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).

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


1
投票

一般来说,这取决于你想要做什么以及你的编程风格。虽然它们都可以工作,但我建议坚持使用更明确的样式,例如你所列出的(3)和(4)。

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

虽然看起来更多的工作,但如果您坚持只根据需要导入所需内容,那么它将导致更容易遵循的更好的程序。

© www.soinside.com 2019 - 2024. All rights reserved.