.
├── brother.py
└── main.py
brother.py
def hi():
print("Hi! I'm your brother.")
main.py
import brother
brother.hi()
.
├── children
│ └── tom.py
└── main.py
tom.py
def hi():
print("Hi! I'm Tom.")
** Good example 1 **:
main.py
from children import tom
tom.hi()
** Good example 2 **:
main.py
import children.tom
children.tom.hi()
** Bad example **: → Need to be packaged (see below)
main.py
import children
children.tom.hi() # >> AttributeError: module 'children' has no attribute 'tom'
Create __init__.py
and treat that directory as a package. In __init__.py
, load the modules contained in the same directory there.
.
├── children
│ ├── __init__.py
│ ├── sushi.py
│ └── tom.py
└── main.py
sushi.py
def hi():
print("Hi! I'm Sushi.")
** Good example **:
In the module, use .
to specify the module to be read with a relative path. (Official Release Notes, [Reference](http://stackoverflow.com/questions/22942650/relative-import-from- init-py-file-throws-error)))
__init__.py
from . import tom
from . import sushi
main.py
import children
children.sushi.hi()
** △ example **: You can also do this
__init__.py
from .tom import hi as tom_hi
from .sushi import hi as sushi_hi
main.py
from children import *
sushi_hi()
** Bad example **
__init__.py
import tom # >> ImportError: No module named 'tom'
import sushi
If it is troublesome to add a module every time, refer to here and read all the files in the same directory.
Recommended Posts