Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

python - module has no attribute

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.

For example:

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

I am trying to import mymodule and access the classes defined in all these files:

from myproject import mymodule

print mymodule.api.MyClass 

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']
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...