Skip to main content
 首页 » 编程设计

python之python 3.5 中的多个相对导入

2025年04月02日9EasonJim

这个结构只是一个例子

pkg\ 
  test\ 
    __init__.py 
    test.py 
  __init__.py 
  source.py 
  another_source.py 

另一个源代码.py

class Bar(): 
  def __init__(self): 
    self.name = "bar" 

源代码.py

from another_source import Bar 
class Foo(): 
  def __init__(self): 
    self.name = "foo" 
    b = Bar() 

测试.py

from ..source import Foo 
 
if __name__== "__main__": 
    f = Foo() 
    print(f.name) 

现在我要运行 test.py。 因为它已被接受为 answer我必须超越我当前的包并运行

python -m pkg.test.test 

但这不起作用,python 给了我一个回溯

Traceback (most recent call last): 
  File "-\Python35\lib\runpy.py", line 170, in _run_module_as_main 
    "__main__", mod_spec) 
  File "-\Python35\lib\runpy.py", line 85, in _run_code 
    exec(code, run_globals) 
  File "~\test\test.py", line 1, in <module> 
    from ..source import Foo 
  File "~\source.py", line 1, in <module> 
    from another_source import Bar 
ImportError: No module named 'another_source' 

如果我删除所有 another_source-stuff 它会起作用,但这不是解决方案。

现在有没有一种明智的方法可以从我上面一个目录的地方导入类?

请您参考如下方法:

pkg.source 正在尝试从 pkg.another_source 模块导入内容,就好像它是顶级模块一样。该导入需要更正:

from .another_source import Bar 
# or 
from pkg.another_source import another_source