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

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