问题:如何获得对模块本身内部模块的引用?

如何从该模块中获取对模块的引用?另外,如何获得包含该模块的包装的参考?

How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?


回答 0

import sys
current_module = sys.modules[__name__]
import sys
current_module = sys.modules[__name__]

回答 1

还有一种技术,它不会导入sys模块,并且可以说-取决于您的口味-更简单:

current_module = __import__(__name__)

请注意,没有导入。Python仅导入每个模块一次。

One more technique, which doesn’t import the sys module, and arguably – depends on your taste – simpler:

current_module = __import__(__name__)

Be aware there is no import. Python imports each module only once.


回答 2

如果在该模块中有一个类,则__module__该类的属性是该类的模块名称。因此,您可以通过访问模块sys.modules[klass.__module__]。这也适用于功能。

If you have a class in that module, then the __module__ property of the class is the module name of the class. Thus you can access the module via sys.modules[klass.__module__]. This is also works for functions.


回答 3

您可以使用获取当前模块的名称 __name__

可以在sys.modules字典中找到模块参考。

请参阅Python 文档

You can get the name of the current module using __name__

The module reference can be found in the sys.modules dictionary.

See the Python documentation


回答 4

您可以从外部传递它:

mymod.init(mymod)

这并不理想,但适用于我当前的用例。

You can pass it in from outside:

mymod.init(mymod)

Not ideal but it works for my current use-case.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。