模块没有属性 [英] module has no attribute
问题描述
我有一个包含许多 .py
文件的目录.每个文件定义了一些类.我的目录中还有一个空的 __init__.py
.
I have a directory with a number of .py
files in it. each file defines some classes. I also have an empty __init__.py
in the directory.
例如:
myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py
我正在尝试导入 mymodule
并访问所有这些文件中定义的类:
I am trying to import mymodule
and access the classes defined in all these files:
from myproject import mymodule
print mymodule.api.MyClass
它给我一个错误,说 mymodule
没有属性 api
.为什么?为什么我只能访问其中一个文件 (models.py
) 而不能访问其他文件?
It gives me an error saying that mymodule
has no attribute api
. Why? And why I can access just one of the files (models.py
) and not the others?
In [2]: dir(banners)
Out[2]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__',
'models']
推荐答案
问题是子模块没有自动导入.您必须显式导入 api
模块:
The problem is submodules are not automatically imported. You have to explicitly import the api
module:
import myproject.mymodule.api
print myproject.mymodule.api.MyClass
如果你真的坚持在导入 myproject.mymodule
时 api
可用,你可以把它放在 myproject/mymodule/__init__.py
中:
If you really insist on api
being available when importing myproject.mymodule
you can put this in myproject/mymodule/__init__.py
:
import myproject.mymodule.api
然后这将按预期工作:
from myproject import mymodule
print mymodule.api.MyClass
这篇关于模块没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!