[...]
For example, it's part of the Google Python style guides[1] that all
imports must import a module, not a class or function from that
module. There are way more classes and functions than there are
modules, so recalling where a particular thing comes from is much
easier if it is prefixed with a module name. Often multiple modules
happen to define things with the same name -- so a reader of the code
doesn't have to go back to the top of the file to see from which
module a given name is imported.
让我把对话的一部分粘贴到由Guido van Rossum开始的django dev邮件列表上:
来源:http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a
1:http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports
在我们公司的生产代码中,我们试图遵循以下规则。
我们将导入放在文件的开头,紧跟在主文件的docstring之后,例如:
现在,如果导入的类是导入模块中为数不多的类之一,则直接导入名称,这样在代码中只需使用最后一部分,例如:
但是,有些模块包含几十个类,例如所有可能的异常列表。然后我们导入模块本身并在代码中引用它:
我们尽可能少地使用
import X as Y
,因为它使搜索特定模块或类的用法变得困难。但是,有时如果希望导入两个同名但存在于不同模块中的类,则必须使用它,例如:一般来说,我们不在方法内部进行导入——它们只是让代码变得更慢,可读性更低。有些人可能会发现这是一个很好的方法来轻松解决循环导入问题,但更好的解决方案是代码重组。
我通常在模块级使用
import X
。如果只需要模块中的单个对象,请使用from X import Y
。只有在遇到名称冲突时才使用
import X as Y
。当模块用作主模块时,我只使用函数级的导入来导入所需的内容,例如:
高温高压
相关问题 更多 >
编程相关推荐