Python 嵌套 import 加载文件, 出现问题求解决

2015-11-19 16:54:14 +08:00
 dai269619118

这是我模拟项目里的一个目录结构

执行文件:main.py

from test2 import pig
print 'hello'

/test2/init.py

from pig import pig

/test2/pig.py

from test1 import dog

class pig(object):
    pass

print 'pig'

/test1/init.py

from dog import dog
from dog1 import dog1

/test1/dog.py

class dog(object):
    pass

print 'dog'

/test1/dog1.py

from test2 import pig

class dog1(object):
    pass

print 'dog1'

执行 main.py 之后就报错了

Traceback (most recent call last):
dog
  File "/opt/svn/tor/other/main.py", line 2, in <module>
    from test2 import pig
  File "/opt/svn/tor/other/test2/__init__.py", line 2, in <module>
    from pig import pig
  File "/opt/svn/tor/other/test2/pig.py", line 2, in <module>
    from test1 import dog
  File "/opt/svn/tor/other/test1/__init__.py", line 2, in <module>
    from dog1 import dog1
  File "/opt/svn/tor/other/test1/dog1.py", line 1, in <module>
    from test2 import pig
ImportError: cannot import name pig

大家帮忙看下 这个问题应该怎么解决

2476 次点击
所在节点    程序员
15 条回复
NeoAtlantis
2015-11-19 18:23:50 +08:00
billgreen1
2015-11-19 18:36:59 +08:00
简单一点的话, dog1.py 和 test2 不在同一层次,改成
from ..test2 import pig
clino
2015-11-19 18:47:27 +08:00
在函数里 import
dai269619118
2015-11-19 21:52:54 +08:00
@NeoAtlantis 已经看过一次了 再看仔细看下
@billgreen1
Traceback (most recent call last):
File "/opt/svn/tor/other/main.py", line 2, in <module>
from test2 import pig
File "/opt/svn/tor/other/test2/__init__.py", line 2, in <module>
from pig import pig
File "/opt/svn/tor/other/test2/pig.py", line 2, in <module>
from test1 import dog
File "/opt/svn/tor/other/test1/__init__.py", line 2, in <module>
from dog1 import dog1
File "/opt/svn/tor/other/test1/dog1.py", line 3, in <module>
from ..test2 import pig
ValueError: Attempted relative import beyond toplevel package
改完还是报错
NeoAtlantis
2015-11-19 22:19:34 +08:00
from test2.pig import pig 试试
billgreen1
2015-11-20 00:23:07 +08:00
哈,这个好玩,模块名,类名一样,而且重复导入
RickyBoy
2015-11-20 01:01:36 +08:00
Python 2 模块和类名相同的确很烦
RickyBoy
2015-11-20 01:36:55 +08:00
好吧,看了看问题应该出在重复导入
dai269619118
2015-11-20 09:21:35 +08:00
@NeoAtlantis 还是不行 ImportError: cannot import name pig
@billgreen1
@RickyBoy
重复导入 有什么办法解决吗?
billgreen1
2015-11-20 11:44:15 +08:00
重新组织你的包吧。你的 test1 要用到 test2 里面的, test2 又要用到 test1 里面的,说明你可以考虑把它们整合到一起。

2.看看 pep8 ,模块名要小写,类名 CamelCase ,导入的时候尽量导入模块,不要导入类,尤其在你写模块的时候。
dai269619118
2015-11-20 12:05:12 +08:00
@billgreen1 恩恩 只能重新组织包了 非常感谢!
walleL
2015-11-20 14:29:22 +08:00
这是循环 import 的问题吧。 A 依赖 B.x, B 依赖 A.x

应该:
1. 重新组织结构,把 A.x 、 B.x 独立出来成一个模块
2. 如果使用 1 的方法不好解决,就在调用函数的内部 import
dai269619118
2015-11-20 15:00:20 +08:00
@walleL 谢谢 已经重新组织了
SmiteChow
2015-11-21 16:44:14 +08:00
循环引用,只能在用到时进行 import 才能避免错误
maijiawei
2015-11-22 09:07:26 +08:00
😍

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/237374

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX