3rd Chapter Module
1. When the code becomes more and more:
We put all the code in a py file: unable to maintain
If we split the code into multiple py files, the variable of the same name will not be affected
2. Module name is file name, then how to apply other modules
Import Math Reference Math module
Print Math.pow (2,10) function calling the Math module
But after more modules will be the same name, conflict resolution: Put in different packages can
Import Module
To use a module, we must first import the module. Python imports a module using the import statement. For example, import the module that comes with the system, math:
Import Math
You can think of math as a variable that points to the imported module, where we can access all the exposed functions, variables, and classes defined in the Math module:
Math.pow (2, 0.5) # POW is a function
1.4142135623730951
Math.PI # pi is a variable
3.141592653589793
If we only want to import some of the functions of the math module used, instead of all the functions, you can use the following statement:
From math import pow, sin, log
In this way, the 3 functions of pow, sin, and log can be referenced directly, but other functions of math are not imported:
Pow (2, 10)
1024.0
Sin (3.14)
0.0015926529164868282
What if I encounter a name conflict? For example, the Math module has a log function, logging module also has a log function, if used simultaneously, how to resolve the name conflict?
If you import the module name using import, there is no conflict because the function name must be referenced through the module name:
Import Math, logging
Print Math.log (10) # called the log function of math
Logging.log (' something ') # called the log function of the logging
If you use From...import to import the log function, it is bound to cause conflicts. At this point, you can give the function an "alias" to avoid the conflict:
From Math import log
The log of from logging import log as Logger # logging now becomes logger
Print log (10) # is called the log of math
Logger (' Import from Logging ') # called the Log of logging
Task
The Python os.path module provides the Isdir () and Isfile () functions, import the module, and invoke the function to determine whether the specified directory and file exists.
Attention:
1. Because the operating environment is a platform server, the test is also the server folder and files, the server has/data/webroot/resource/python folder and/data/webroot/resource/python/ Test.txt file, everyone can test under.
2. Of course, you can test the existence of the corresponding folders and files on this computer.
Import OS
Print Os.path.isdir (R ' C:\Windows ')
Print Os.path.isfile (R ' C:\Windows\notepad.exe ')
Note that the Os.path module can be imported in several ways:
Import OS
Import Os.path
From OS import path
From Os.path import Isdir, isfile
Every way calls Isdir and Isfile are different.
Reference code:
Import OS
Print Os.path.isdir (R '/data/webroot/resource/python ')
Print Os.path.isfile (R '/data/webroot/resource/python/test.txt ')
Dynamic Import Module
If the imported module does not exist, the Python interpreter will report a importerror error:
Import something
Traceback (most recent):
File "", Line 1, in
Importerror:no module named something
Sometimes, two different modules provide the same functionality, such as Stringio and Cstringio, which provide Stringio.
This is because Python is a dynamic language that interprets execution, so Python code runs slowly.
If you want to improve the speed of Python code, the simplest way is to rewrite some key functions in C, which can greatly improve the execution speed.
The same functionality, Stringio is written in pure Python code, while the Cstringio part of the function is written in C, so Cstringio runs faster.
With Importerror errors, we often import modules dynamically in Python:
Try
From Cstringio import Stringio
Except Importerror:
From Stringio import Stringio
The above code attempts to import from Cstringio first, and if it fails (for example, Cstringio is not installed), try importing from Stringio. This way, if the Cstringio module is present, we will get a faster run, and if Cstringio does not exist, the code will run slower, but it will not affect the normal execution of the code.
The action of the try is to catch the error and execute the except statement when the specified error is caught.
Task
Using import ... as ..., you can also dynamically import modules of different names.
The Python 2.6/2.7 provides a JSON module, but Python 2.5 and earlier do not have JSON modules, but you can install a Simplejson module that provides the same function signatures and functions as the two modules.
Try to write the code to import the JSON module, which will work correctly in Python 2.5/2.6/2.7.
Try importing the JSON first, and if it fails, try importing the Simplejson as JSON
Reference code:
Try
Import JSON
Except Importerror:
Import Simplejson as JSON
Print json.dumps ({' Python ': 2.7})
Use Future
New versions of Python introduce new features, but in fact these features already exist in the previous version. To "Try" a new feature, you can import FutureSome of the functionality of the module.
For example, the integer division operation of Python 2.7 is still an integer:
10/3
3
However, Python 3.x has improved the division of integers, "/" in addition to the floating-point number, "//" is still an integer:
10/3
3.3333333333333335
10//3
3
To introduce a 3.x division rule in Python 2.7, import FutureThe Division:
From FutureImport Division
Print 10/3
3.3333333333333335
When a feature of a new version is incompatible with an older version, the feature will be added to the old version in the FutureSo that the old code can test the new feature in the old version.
Task
In Python 3.x, string unification is Unicode, no prefix u is required, and str stored in bytes must be prefixed with B. Please use FutureThe Unicode_literals writes a Unicode string in Python 2.7.
Using the From FutureImport Unicode_literals will bring the Python 3.x Unicode rules into Python 2.7.
Reference code:
From FutureImport Unicode_literals
s = ' am I an Unicode? '
Print isinstance (s, Unicode)
To install a third-party module:
The module management tools provided by Python:
There are three ways to install a non-self-contained Python module in Python:
1. Easy_install
2. PIP (recommended, already built into python2.7.9)
3. After downloading the compressed package (. zip,. tar,. tar.gz), unzip and go to the extracted directory and execute the Python setup.py install command
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
About the Python module, maybe this: