擅长:python、mysql、java
<p>假设您的目录结构如下:</p>
<pre><code>./ <- you are here
- main.py
- my_package/
- __init__.py
- my_module.py
</code></pre>
<p>您还需要动态导入<code>my_module.py</code>,以使用它的一些函数、类等。然后,使用<code>importlib</code>,可以在<code>main.py</code>中使用以下代码:</p>
<pre class="lang-py prettyprint-override"><code>import importlib
pack = "my_package"
mod = "my_module"
module = importlib.import_module("." + mod, pack)
# or, alternatively
module = importlib.import_module(".".join(pack, mod))
module.func("hello") # if my_package/my_module.py defines function "func"
obj = module.MyClass("world") # if my_package/my_module.py defines class "MyClass"
</code></pre>