问题
I have a question. I have a directory setup like this:
folder/
main.py
/stuff/
__init__.py
function.py
/items/
__init__.py
class.py
My question is how would I import the class.py into the function.py? This setup is very specific and is unable to be changed. What would I need to put in order for this to work?
回答1:
Your current directory structure seems ideal, so long as the application is started via main.py
.
Python will always automatically add the parent directory of the main script to the start of sys.path
(i.e. folder
in your example). This means that the import machinery will give that directory priority when searching for modules and packages that are not part of the standard libarary.
Given this, you can import the classes.py
module into function.py
, like so:
from items import classes
(Note that I have renamed the module, because class
is a python keyword).
If you later added another module to stuff
, and wanted to import it into functions.py
, you would do:
from stuff import another
and if a sub-package was added to items
, and you wanted to import a module from that, you would do:
from items.subpackage import module
Imports specified in this top-down way can be used from any module within the application, because they are always relative to the parent directory of the main script, which has priority.
来源:https://stackoverflow.com/questions/27344641/python-importing-from-parents-child-folder