Python: Import module calls summary

Python module basic situation [ See ]

  • import
    directly introduced module
  • from ... import
    import a part from a specified module into the current namespace
  • ... Import from *
    all the contents of a module all into the current namespace
    Note : generally not recommended to import all the way to the last, there is a potential danger. For example, while introducing the module2 module1 and all content, when two modules contain a foo () function, the following code is executed when the program is added:
`foo()`

At this time can not be determined foo () is a function module belongs.

Python package

Package is the folder, but there must be _init_.py files in the folder, the contents of the file can be empty. Which is used to identify the current folder is a package.
Only module contains _init_.py files can only be invoked

File directory list

Contents List

Call the same directory

file1 and file2 to the same directory
dataProcess.py, kmeans.py and kmeans-test.py to the same directory

- the same subdirectory

When (a) in the same directory file2, when you need to call kmeans.py in method () method in the kmeans-test.py

# kmeans-test.py
import kmeans

kmeans.method()
# kmeans-test.p
from kmeans import method

method()

- different subdirectory

(B) In file1 and file2, respectively, when the need to call the method in dataProcess.py kmeans.py () method

# dataProcess.py
# 跳转目录
import sys
sys.path.append('..')  # 1.回到上一级目录file1
from file2 import kmeans  # 2.再从file1的同级目录file2下去寻找kmeans.py模块

kmeans.method()

Non-peer call directory

non file2 and file3 same directory
file3 kmeans-test.py to the same directory and
when (iii) the need to call the method kmeans1.py file2 file3 in the kmeans-test.py () method

# kmeans-test.py
from file3 import kmeans1

kmeans1.method()

If the direct import kmeans1will fail, because kmeans-test.py with kmeans1.py not on the same level directory, you need to peer through its file3 directory to fromfind kmeans1.py module (in the case of the same nature (a) in the second call methods )
Note : the file directory levels, and py file py file method may be regarded as a module to discuss, directory level (path) is the impact of the key issues of whether the call was successful

Successfully transferred key points

  1. init.py
  2. Search path called correctly (sys.path.append ( 'path'))

Reference learning materials

Python: sys.path Details
Python: ImportError: No Module named 'XXX'
Python module [cross-directory] call summary

Wing ~

Released eight original articles · won praise 3 · Views 649

Guess you like

Origin blog.csdn.net/lehek/article/details/104129570