Python导入:AttributeError:';模块';对象没有属性';测试';
我认为这是一个愚蠢的问题,但我不明白为什么我会得到以下结果Python导入:AttributeError:';模块';对象没有属性';测试';,python,python-import,Python,Python Import,我认为这是一个愚蠢的问题,但我不明白为什么我会得到以下结果 AttributeError: 'module' object has no attribute 'test' 运行我的test3.py时 这是我的项目树: . ├── __init__.py ├── test3.py └── testdir ├── __init__.py └── test.py Mytest3.py: #!/usr/bin/python
AttributeError: 'module' object has no attribute 'test'
运行我的test3.py时
这是我的项目树:
.
├── __init__.py
├── test3.py
└── testdir
├── __init__.py
└── test.py
Mytest3.py:
#!/usr/bin/python
import testdir
if __name__ == "__main__":
print(testdir.test.VAR)
#!/usr/bin/python
import os
VAR=os.path.abspath(__file__)
Mytest.py:
#!/usr/bin/python
import testdir
if __name__ == "__main__":
print(testdir.test.VAR)
#!/usr/bin/python
import os
VAR=os.path.abspath(__file__)
我还尝试通过以下方式导入我的VAR:
from testdir.test import VAR
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
编辑:现在这一个可以工作了-多亏了@user2357112-但是我仍然想知道如何在没有的情况下从。。。导入…
如果可能的话:
我尝试了一个import..testdir
来进行相对导入,但得到了一个SyntaxError
如果我尝试导入testdir.test我会得到一个
名称错误:名称“test”未定义
如何导入此文件?我有点困惑
编辑bis:
很抱歉,当我尝试导入testdir.test时,我还将
print(testdir.test.VAR)
修改为print(test.VAR)
这就是问题所在,我的错
与:
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
它工作得很好,我认为导入testdir.test
使test
在范围内单独存在(而不是testdir.test
)
很抱歉给您带来不便S尝试将
from.test导入VAR
添加到testdir/init.py。然后导入testdir
在test3.py中打印testdir.VAR可能会起作用。我同意这更多的是一种变通方法,而不是解决方案。要在不使用导入语句的情况下添加整个文件,您可以使用我最终成功地使其以这种方式工作:
from testdir.test import VAR
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
当我尝试导入testdir.test时,我错误地将
print(testdir.test.VAR)
修改为print(test.VAR)
。所以我犯了这个名字错误
我的错。在你的实际文件中,
vAR
是这样大写的吗?我的错,你是对的。现在,testdir.test import VAR的工作了,谢谢。但是我如何才能导入整个文件而不使用来自。。。导入…
?导入testdir.test
。导入包不会自动加载其子模块。我尝试了此操作,但出现了名称错误。我不知道这一个,谢谢。但如果我使用它,在某些情况下,它可能会擦除一些对象。不过,我会把它用于其他用途。这个变通方法确实有效,谢谢。)我注意到这样做,我不知道(我不了解进口的一切)。但你是对的:这是一个解决办法,把这样的导入放到_init_uuy.py中不是很肮脏吗?无论如何,我终于发现了问题(我的问题出了一个错误,所以没有人能给我问题的答案,我的坏:S)。不,将导入放入init文件本身并不是“脏”的,事实上,它的名称表明它是用于初始化包的。它提供了一种封装,在这种封装中,包的用户不需要知道包的内部结构和模块。话虽如此,导入init do中的所有内容会使名称空间变得混乱。所以明智地使用它。