Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

package - Python error: AttributeError: 'module' object has no attribute

I'm totally new to Python and I know this question was asked many times, but unfortunately it seems that my situation is a bit different... I have created a package (or so I think). The catalog tree is like this:

mydir
    lib   (__init__.py)
        mod1  (__init__.py, mod11.py)

In parenthesis there are files in the catalog. Both __init__.py files are zero length.

The file mydir/lib/mod1/mod11.py contains the following:

def mod12():
    print "mod12"

Now, I run python, then import lib, which works OK, then lib.mod11() or lib.mod12().

Either of the last two gives me the subject error message. Actually dir(lib) after Step 2 does not display mod11 or mod12 either. It seems I'm missing something really simple.

(I'm using Python 2.6 in Ubuntu 10.10)

Thank you

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...