为什么要返回包而不是模块?

2024-10-17 02:37:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的文件结构(其中点是我的工作目录):

.
+-- testpack
     +-- __init__.py
     +-- testmod.py

如果我用import语句加载testmod模块,我可以调用在以下内容中声明的函数:

^{pr2}$

但是,如果我尝试使用__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

怎么了?在


Tags: 模块文件函数pyimport目录声明init
1条回答
网友
1楼 · 发布于 2024-10-17 02:37:33

此行为在the docs中给出:

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

。。。在

The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], -1)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

还要注意顶部的警告:

This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

后来:

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

所以这里的解决方案是使用^{}。在

值得注意的是,在Python中,名称两边的双下划线意味着在大多数情况下,手头的对象并不打算直接使用。正如您通常应该使用len(x)over x.__len__()或{}/dir(x)超过x.__dict__。除非你知道你为什么要用它,否则这通常是一个信号,有问题。在

相关问题 更多 >