Python 属性错误:';模块';对象没有属性';x';
我正在阅读从中加载的模块 我的一个目录Python 属性错误:';模块';对象没有属性';x';,python,Python,我正在阅读从中加载的模块 我的一个目录mod_a.py和mod_b.py中有两个文件 mod_a.py包含以下内容 print 'at top of mod_a' import mod_b print 'mod_a: defining x' x = 5 而mod_b.py包含 print 'at top of mod_b' import mod_a print 'mod_b: defining y' y = mod_a.x 在执行mod_a.py文件时,我得到了以下输出: at top of
mod_a.py
和mod_b.py
中有两个文件
mod_a.py
包含以下内容
print 'at top of mod_a'
import mod_b
print 'mod_a: defining x'
x = 5
而mod_b.py
包含
print 'at top of mod_b'
import mod_a
print 'mod_b: defining y'
y = mod_a.x
在执行mod_a.py
文件时,我得到了以下输出:
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
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'
但是,在执行mod_b.py
时,我得到了以下输出:
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
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'
模块b顶部的
在mod_a的顶部
在mod_b的顶部
mod_b:定义y
回溯(最近一次呼叫最后一次):
文件“D:\Python\Workspace\Problems-2\mod_b.py”,第2行,在
导入模块a
文件“D:\Python\Workspace\Problems-2\mod_a.py”,第2行,在
导入模块b
文件“D:\Python\Workspace\Problems-2\mod_b.py”,第4行,在
y=mod_a.x
AttributeError:“模块”对象没有属性“x”
有人能解释一下吗?代码在这一行失败了
import mod_a
因为它将通过mod_a.py
运行,这将导入mod_b.py
,其中mod_a.x
尚未定义
为清楚起见,请参见mod_b
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
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
你有一个循环导入。不要那样做;这就是当你这样做时会发生的事情。@user2357112,谢谢,我已经尝试了这个来学习和练习。你能解释一下循环进口到底是如何困扰这里的吗?我想这个答案会有所帮助:一个精确的复制品