假设我有两个Python模块:
module1.py
:
import module2
def myFunct(): print "called from module1"
module2.py
:
如果我导入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
的导入?在
引用PEP 8 style guide:
强调我的。在
不要使用
module1.module2
;您依赖的是module1
的内部实现细节,这可能会在以后更改它所使用的导入。您可以直接导入module2
,除非模块作者另有说明,否则请这样做。在您可以使用^{} convention 来限制从带有
from modulename import *
的模块导入的内容;help()
命令也遵循该列表。列出您在__all__
中显式导出的名称有助于清理help()
文本演示:只要
import module2
。由于Python将模块对象缓存在sys.modules中,因此重新导入相对来说没有成本。在此外,}。通过使用}的所有出现。在
module1.module2.myFunct
中的链式点违反了Law of Demeter。也许有一天你会想用另一个不导入module2
的模块来替换{import module2
,您将避免重写{from module2 import *
通常是一种不好的做法,因为它使跟踪变量的来源变得困难。混合模块名称空间可能会导致变量名冲突。例如,from numpy import *
是一个明确的no,因为这样做会覆盖Python的内置代码sum
、min
、max
、any
、all
、abs
和{相关问题 更多 >
编程相关推荐