开发者

Python Modules not Being Found?

I'm new to Python, trying to get to know how to properly set up a Module.

I have the following:

 dir1
    pack1.py
        dir2
           pack2.py

...and of course in my directories I have __init__.py

Now, I am trying to get pack2.py to be inherited from pack1.py

Got the following:

class Pack2(Pack1):
    def __repr__(self):
       ....my code goes here....

And I want to import this into my program so I can use Pack2

My Problem: I'm having a terrible time trying to figure out the import statement to use in my program and in the pack2.py file.

I tried (in my program):

from dir1.dir2 import pack2

and in Pack2

from dir1 import pack1

b开发者_如何学Cut no dice. Does this seem correct?


In python doing import module doesn't make all names defined in module directly available in current namespace... you need to use module.name to access them. If you want to get all names defined in a module directly available you have to do something like from module import *.

To be able to tell for sure where the problem is the content of your __init__.py files should be shown, but assuming that they are empty files created just to use the subdirectories as modules then I think you should use:

  • In main program from dir1.dir2.pack2 import Pack2
  • In pack1.py instead you should use from dir2.pack2 import Pack2


Have you set your Python path? If you haven't then the Python interpreter is unlikely to be able to find all of your modules.

Each script's directory is in the Python path, so modules can import other modules in the same, or lower directories. But modules that need to import things from parent directories need to do a little extra work.

The solution is to modify sys.path:

import sys
# Add parent directory to path
sys.path.append('..')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜