8. What is a module? module import __name __, module _ name _
What is a module:
In Python, modules are the repositories of methods and classes. If we want to use a method or class, we need to import the corresponding template.
[Python has built-in methods and classes, so we do not need to import modules for some methods]
Module usage: module. function, module. Class
Module import:
# From Module name import class name, method name from collections import Iterable print (isinstance ("abc", Iterable) print (isinstance ([1, 2, 3], Iterable ))
- From... During import, you can also give the imported part a custom name, for example, from... Import funcA as fa
Search Path of Python import
1. Search for this module in the current directory
2. Search for the path list specified in the environment variable PYTHONPATH in sequence [available from sys. path]
Import sysprint (sys. path) ---------- running result: ['J: \ HardWork \ Code \ python', 'J: \ HardWork \ Code \ python', 'I: \ python3 \ python36.zip ',' I :\\ python3 \ DLLs ',' I: \ python3 \ lib ',' I :\\ python3 ', 'I: \ python3 \ lib \ site-packages']
3. Search for the lib library in the Python installation path
Directory structure:
C content:
How to import c in B:
Import sys, osprint (_ file _) # This is the absolute path of the current file, parent_dir = OS. path. dirname (_ file _) # obtain the directory pp_dir = OS of the current file. path. dirname (parent_dir) sys. path. append (pp_dir) # print (sys. path) import c # To import c, you must add diff_dir to sys. path
_ Name __:
Since the module can be imported or run directly, to distinguish the content that runs when running directly, you have _ name __:
When running directly, __name _ is _ main __:
Print ("import C done") print (_ name _) if _ name __= = '_ main _': print ("direct run ") --------------- run result: import C done _ main _ direct run
When used for import, __name _ is the name of the currently imported module. Because _ name _ is not equal to _ main __, it is not executed:
Import sys, OS # print (_ file _) # This is the absolute path of the current file, parent_dir = OS. path. dirname (_ file _) # obtain the directory pp_dir = OS of the current file. path. dirname (parent_dir) sys. path. append (pp_dir) # print (sys. path) import c # To import c, you must add diff_dir to sys. in path ------------------ running result: import C donec