AttributeError: 'module' object has no attribute 'x'
本问题已经有最佳答案,请猛点这里访问。
我在这里读模块的加载。
我的目录
1 2 3 4 | print 'at top of mod_a' import mod_b print 'mod_a: defining x' x = 5 |
而
1 2 3 4 | print 'at top of mod_b' import mod_a print 'mod_b: defining y' y = mod_a.x |
在执行
1 2 3 4 5 6 | at top of mod_a at top of mod_b at top of mod_a mod_a: defining x mod_b: defining y mod_a: defining x |
但是,在执行
1 2 3 4 5 6 7 8 9 10 11 12 | at top of mod_b at top of mod_a at top of mod_b mod_b: defining y Traceback (most recent call last): File"D:\Python\Workspace\Problems-2\mod_b.py", line 2, in <module> import mod_a File"D:\Python\Workspace\Problems-2\mod_a.py", line 2, in <module> import mod_b File"D:\Python\Workspace\Problems-2\mod_b.py", line 4, in <module> y = mod_a.x AttributeError: 'module' object has no attribute 'x' |
有人能解释一下吗?
代码在这一行失败
1 | import mod_a |
因为它将运行于
为清楚起见,请参阅
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | print 'at top of mod_b' import mod_a # Importing a... print 'at top of mod_a' import mod_b # Importing b... print 'at top of mod_b' import mod_a # ... will happen, but... print 'mod_b: defining y' y = mod_a.x # error print 'mod_a: defining x' x = 5 print 'mod_b: defining y' y = mod_a.x |
与
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | print 'at top of mod_a' import mod_b # Importing b... print 'at top of mod_b' import mod_a # Importing a... print 'at top of mod_a' import mod_b # Recurses... print 'mod_a: defining x' x = 5 # definition print 'mod_b: defining y' y = mod_a.x # it's defined... no error print 'mod_a: defining x' x = 5 |