Use the import method in python: 1. [import module_name], that is, the module name is directly connected after import; 2. [from package_name import module_name] is a collection of modules.
The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.
Use the import method in python:
First, create a folder Tree as the working directory, and create two files m1.py and m2 in it .py, write code in m1.py:
import os import m2 m2.printSelf()
Write code in m2.py:
def printSelf(): print('In m2')
Open the command line, enter the Tree directory, type python m1.py and run , found that no error was reported, and In m2 was printed, indicating that there is no problem using import in this way. From this we summarize the first usage of the import statement.
<strong>import module_name</strong>
. That is, the module name is directly connected after import. In this case, Python will look for this module in two places. The first is sys.path (check it by running the code import sys; print(sys.path)). The directory where the os module is located is in the list sys.path , the directories of generally installed Python libraries can be found in sys.path (the premise is to add the Python installation directory to the computer's environment variables), so for the installed libraries, we can directly import them. The second place is the directory where the running file (here, m1.py) is located. Because m2.py and the running file are in the same directory, there is no problem with the above writing method.
There is no problem in importing the library in the original sys.path using the above method. However, it is best not to use the above method to import files in the same directory! Because this can go wrong. To demonstrate this error, you need to use the second way of writing the import statement, so let's learn the second way of writing import first. Create a new directory Branch under the Tree directory, and create a new file m3.py in Branch. The content of m3.py is as follows:
def printSelf(): print('In m3')
How to import m3.py into m1, please see the changed m1.py :
from Branch import m3 m3.printSelf()
Summarize the second usage of the import statement:
##from package_name import module_name<strong></strong>
. Generally, a collection of modules is called a package. Similar to the first way of writing, Python will look for the package in two places: sys.path and the running file directory, and then import the module named module_name in the package.
def printSelf(): print('In m4')
import m4 def printSelf(): print('In m3')
from . import m4 def printSelf(): print('In m3')
Related free learning recommendations:
The above is the detailed content of How to use import in python. For more information, please follow other related articles on the PHP Chinese website!