我有这样的文件结构(其中点是我的工作目录):
.
+-- testpack
+-- __init__.py
+-- testmod.py
如果我用import
语句加载testmod
模块,我可以调用在以下内容中声明的函数:
但是,如果我尝试使用__import__()
函数执行相同的操作,它将不起作用:
>>> __import__("testpack.testmod").testfun()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
__import__("testpack.testmod").testfun()
AttributeError: 'module' object has no attribute 'testfun'
实际上,它返回包testpack
,而不是模块testmod
:
>>> __import__("testpack.testmod").testmod.testfun()
hello
怎么了?在
此行为在the docs中给出:
。。。在
还要注意顶部的警告:
后来:
所以这里的解决方案是使用^{} 。在
值得注意的是,在Python中,名称两边的双下划线意味着在大多数情况下,手头的对象并不打算直接使用。正如您通常应该使用}/
len(x)
overx.__len__()
或{dir(x)
超过x.__dict__
。除非你知道你为什么要用它,否则这通常是一个信号,有问题。在相关问题 更多 >
编程相关推荐