假设我有两个 Python 模块:
module1.py
:
import module2
def myFunct(): print "called from module1"
module2.py
:
def myFunct(): print "called from module2"
def someFunct(): print "also called from module2"
如果我导入 module1
,重新导入 module2
还是只引用 module1.module2
更好?
例如(someotherfile.py
):
import module1
module1.myFunct() # prints "called from module1"
module1.module2.myFunct() # prints "called from module2"
我也可以这样做:module2 = module1.module2
。现在,我可以直接调用 module2.myFunct()
。
但是,我可以将 module1.py
更改为:
from module2 import *
def myFunct(): print "called from module1"
现在,在 someotherfile.py
中,我可以这样做:
import module1
module1.myFunct() # prints "called from module1"; overrides module2
module1.someFunct() # prints "also called from module2"
此外,通过导入 *
,help('module1') 显示了 module2
中的所有函数。
另一方面,(假设 module1.py
使用 import module2
),我可以这样做:
someotherfile.py
:
import module1, module2
module1.myFunct() # prints "called from module1"
module2.myFunct() # prints "called from module2"
同样,礼仪和实践哪个更好?再次引入module2
,还是只引用module1
的引入?
最佳答案
When importing a class from a class-containing module, it's usually okay to spell this:
from myclass import MyClass from foo.bar.yourclass import YourClass
If this spelling causes local name clashes, then spell them
import myclass import foo.bar.yourclass
强调我的。
不要使用module1.module2
;您依赖于 module1
的内部实现细节,稍后可能会更改它使用的导入内容。您可以直接导入 module2
,除非模块作者另有说明,否则请这样做。
您可以使用 __all__
convention使用 from modulename import *
限制从模块导入的内容; help()
命令也支持该列表。列出您在 __all__
中显式导出的名称有助于清理 help()
文本表示:
The public names defined by a module are determined by checking the module’s namespace for a variable named
__all__
; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in__all__
are all considered public and are required to exist. If__all__
is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'
).__all__
should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).
关于Python 礼仪 : Importing Modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385156/