Python导入:AttributeError:'module'对象没有属性'test'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30826636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python import : AttributeError: 'module' object has no attribute 'test'
提问by vmonteco
I think that's stupid problem, but I can't figure out why I get the following
我认为这是一个愚蠢的问题,但我不明白为什么我得到以下
AttributeError: 'module' object has no attribute 'test'
when running my test3.py.
运行我的test3.py 时。
Here is my project tree :
这是我的项目树:
.
├── __init__.py
├── test3.py
└── testdir
├── __init__.py
└── test.py
My test3.py:
我的test3.py:
#!/usr/bin/python
import testdir
if __name__ == "__main__":
print(testdir.test.VAR)
My test.py:
我的test.py:
#!/usr/bin/python
import os
VAR=os.path.abspath(__file__)
I also tried to import my VARthis way :
我也尝试以这种方式导入我的VAR:
from testdir.test import VAR
EDIT:Now this one works -thanks to @user2357112- but I would still like to know how to import the whole test.py file without a from ... import ...
if it is possible. :)
编辑:现在这个工作 - 感谢@ user2357112 - 但我仍然想知道from ... import ...
如果可能的话,如何在没有 a 的情况下导入整个 test.py 文件。:)
And I tried a import ..testdir
to do a relative import but I got a SyntaxError
.
我试图import ..testdir
做一个相对导入,但我得到了一个SyntaxError
.
And if I try import testdir.test
I get a NameError: name'test' is not defined
.
如果我尝试,import testdir.test
我会得到一个NameError: name'test' is not defined
.
How could I import this file? I'm a bit confused.
我怎么能导入这个文件?我有点困惑。
EDIT bis :
编辑之二:
I apologize, when I tried import testdir.test
, I also modified print(testdir.test.VAR)
to print(test.VAR)
.
我道歉,当我尝试时import testdir.test
,我也修改print(testdir.test.VAR)
为print(test.VAR)
.
That was the problem, my bad.
这就是问题所在,我的错。
with :
和 :
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
It works perfectly, I though that importing testdir.test
made test
exist alone (and not testdir.test
) in the scope.
它完美的作品,我虽然那进口testdir.test
作出test
单独(不存在testdir.test
)的范围。
Sorry for the inconvenience. :S
带来不便敬请谅解。:S
采纳答案by vmonteco
I finally succeed to make it work this way :
我终于成功地让它以这种方式工作:
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
I erroneously modified print(testdir.test.VAR)
to print(test.VAR)
when I tried with import testdir.test
. So I had this NameError.
我错误地修改print(testdir.test.VAR)
来print(test.VAR)
当我尝试import testdir.test
。所以我有这个 NameError。
My bad.
我的错。
回答by hspandher
Try adding from .test import VAR
to testdir/init.py. Then import testdir
print testdir.VAR
in test3.py might work. I agree it is more of a workaround than solution.
尝试添加from .test import VAR
到 testdir/ init.py。然后import testdir
print testdir.VAR
在 test3.py 中可能会起作用。我同意这更像是一种解决方法而不是解决方案。