模块没有属性

我有一个目录,其中包含许多 .py文件。每个文件定义一些类。目录中还有一个空的 __init__.py

例如:

myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py

我尝试导入 mymodule并访问所有这些文件中定义的类:

from myproject import mymodule


print mymodule.api.MyClass

它给出了一个错误说明 mymodule没有属性 api。为什么?为什么我只能访问其中一个文件(models.py)而不能访问其他文件?

In [2]: dir(banners)
Out[2]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__',
'models']
134661 次浏览

Modules don't work like that.

from myproject.mymodule import api
print api.MyClass

You need an __init__.py in the myproject directory too. So your module structure should be:

myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py

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

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

Then this will work as expected:

from myproject import mymodule


print mymodule.api.MyClass

If you are an idiot, like me, then also check whether you didn't name your python file the same as the module you are trying to import.