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

执行文件: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
大家帮忙看下 这个问题应该怎么解决
|  |      1NeoAtlantis      2015-11-19 18:23:50 +08:00 via Android  1 | 
|      2billgreen1      2015-11-19 18:36:59 +08:00  1 简单一点的话, dog1.py 和 test2 不在同一层次,改成 from ..test2 import pig | 
|  |      3clino      2015-11-19 18:47:27 +08:00  1 在函数里 import | 
|  |      4dai269619118 OP @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 改完还是报错 | 
|  |      5NeoAtlantis      2015-11-19 22:19:34 +08:00  1 from test2.pig import pig 试试 | 
|      6billgreen1      2015-11-20 00:23:07 +08:00  1 哈,这个好玩,模块名,类名一样,而且重复导入 | 
|  |      7RickyBoy      2015-11-20 01:01:36 +08:00  1 Python 2 模块和类名相同的确很烦 | 
|  |      8RickyBoy      2015-11-20 01:36:55 +08:00 好吧,看了看问题应该出在重复导入 | 
|  |      9dai269619118 OP | 
|      10billgreen1      2015-11-20 11:44:15 +08:00  1 重新组织你的包吧。你的 test1 要用到 test2 里面的, test2 又要用到 test1 里面的,说明你可以考虑把它们整合到一起。 2.看看 pep8 ,模块名要小写,类名 CamelCase ,导入的时候尽量导入模块,不要导入类,尤其在你写模块的时候。 | 
|  |      11dai269619118 OP @billgreen1 恩恩    只能重新组织包了 非常感谢! | 
|      12walleL      2015-11-20 14:29:22 +08:00  1 这是循环 import 的问题吧。 A 依赖 B.x, B 依赖 A.x 应该: 1. 重新组织结构,把 A.x 、 B.x 独立出来成一个模块 2. 如果使用 1 的方法不好解决,就在调用函数的内部 import | 
|  |      13dai269619118 OP @walleL 谢谢    已经重新组织了 | 
|  |      14SmiteChow      2015-11-21 16:44:14 +08:00 循环引用,只能在用到时进行 import 才能避免错误 | 
|  |      15maijiawei      2015-11-22 09:07:26 +08:00 via Android 😍 |