问题
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?
回答1:
import sys
current_module = sys.modules[__name__]
回答2:
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:
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.
回答4:
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
回答5:
You can pass it in from outside:
mymod.init(mymod)
Not ideal but it works for my current use-case.
来源:https://stackoverflow.com/questions/1676835/how-to-get-a-reference-to-a-module-inside-the-module-itself