关于python:attributeError:’module’对象没有属性’x’

AttributeError: 'module' object has no attribute 'x'

本问题已经有最佳答案,请猛点这里访问。

我在这里读模块的加载。

我的目录mod_a.pymod_b.py中有两个文件。

mod_a.py包含以下内容

1
2
3
4
print 'at top of mod_a'
import mod_b
print 'mod_a: defining x'
x = 5

mod_b.py包含

1
2
3
4
print 'at top of mod_b'
import mod_a
print 'mod_b: defining y'
y = mod_a.x

在执行mod_a.py文件时,我得到了以下输出:

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

但是,在执行mod_b.py时,我得到了以下输出:

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

因为它将运行于mod_a.py,而mod_b.py是进口的,而mod_a.x尚未定义。

为清楚起见,请参阅mod_b的"跟踪"

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

mod_a相比

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