Modules allow you to logically organize your Python code snippets.
Assigning the relevant code to a module will make your code better and easier to understand.
The module is also a Python object, with a random name attribute used to bind or reference.
Simply put, the module is a file that holds the Python code. Modules can define functions, classes, and variables. The module can also contain executable code.
Example
A python code in a module called Aname can usually be found in a file called aname.py. The following example is a simple module common.py.
def printfunc (param): Print (("hello:{0}". Format (param))) return
Import statement
To use a Python source file, simply execute the import statement in another source file with the following syntax:
import module1[, module2[,... Modulen]
When the interpreter encounters an import statement, the module is imported if it is in the current search path.
A search path is a list of all directories that an interpreter will search first. To import the module common.py, you need to place the command at the top of the script:
# Import Module Import Common # call the function in the module Common.printfunc ("name")
From...import statements
The FROM statement of Python lets you import a specified section from the module into the current namespace. The syntax is as follows:
From ModName import name1[, name2[, ... Namen]]
For example, to import the Fibonacci function of a module FIB, use the following statement:
From fib import Fibonacci
Instance:
We're adding a method to the common.py.
def printfunc (param): Print (("hello:{0}". Format (param))) return def printFunc1 (param): Print (("hello1:{0}". Format (param))) return
Then introduce PRINTFUNC1
from Import printfunc1printfunc1 ("printFunc1")
Did you find out? From...import introduces a function that does not need to use the module name to call directly
from...import* statements
It is also possible to import all the contents of a module into the current namespace, just use the following declaration:
From ModName Import *
This provides an easy way to import all the items in a module
Namespaces and Scopes
A Python expression can access variables in the local namespace and in the global namespace. If a local variable and a global variable have the same name, the local variable overrides the global variable.
Each function has its own namespace. The scope rules of a method of a class are the same as the usual functions.
Python intelligently guesses whether a variable is local or global, and assumes that any variable that is assigned within the function is local.
Therefore, if you want to assign a value to a global variable in a function, you must use the global statement.
The expression for global varname tells Python that VarName is a global variable so that Python does not look for the variable in the local namespace.
For example, we define a variable money in the global namespace. We then assign a value to the variable money within the function, and then Python assumes that money is a local variable. However, we did not declare a local variable money before the visit, and the result is a unboundlocalerror error. Canceling the comment on the global statement will solve this problem
Money = $def Addmoney (): # to correct the code, uncomment the following: # Global Money Print moneyaddmoney ()print money
Dir () function
The Dir () function is a well-ordered list of strings, and the content is a name defined in a module.
The returned list contains all the modules, variables, and functions defined in a module. Here is a simple example:
Import= dir (Common)print(list)
Output Result:
Packages in Python
A package is a form of managing a Python module namespace, with a "point module name".
For example, the name of a module is A.B, then he represents a sub-module B in Package A.
As if using a module, you don't have to worry about the interaction between the global variables of different modules, and the use of the name of the point module does not have to worry about the names of the modules in different libraries.
This allows different authors to provide a NumPy module, or a Python graphics library.
Suppose you want to design a module that unifies the processing of sound files and data (or "packages").
There are many different types of audio file formats (basically differentiated by suffix names, for example:. wav,:file:.aiff,:file:.au,), so you need to have a constantly growing set of modules that you can use to convert between different formats.
And for these audio data, there are many different operations (such as mixing, adding echoes, adding equalizer functions, creating a man-made stereo effect), and you need a set of modules that can't be written up to handle these operations.
A possible package structure (in a layered file system) is given here:
sound/ Top-level package __init__.py Initialize sound package formats/ file Format Conversion sub-package __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Sound Effects sub-package __init__.py echo.py surround.py reverse.py ... filters/ Filters Sub-package __init__.py equalizer.py vocoder.py karaoke.py ...
When importing a package, Python looks for subdirectories contained in the package based on the directories in the Sys.path.
A directory that contains only a file called __init__.py is considered a package, primarily to avoid the misuse of names (such as String) that inadvertently affects valid modules in the search path.
In the simplest case, put an empty one: the file:__init__.py is ready. Of course, this file can also contain some initialization code or assign a value to the __all__ variable (to be described later).
Users can import only a specific module within a package at a time, such as:
Import Sound.effects.echo
This will import the submodule: Mod:song.effects.echo. He must use his full name to access:
Sound.effects.echo.echofilter (input, output, delay=0.7, atten=4)
Another way to import submodules is to:
From sound.effects import Echo
This also imports the Submodule: Mod:echo, and he doesn't need those lengthy prefixes, so he can use this:
Echo.echofilter (input, output, delay=0.7, atten=4)
Another change is to directly import a function or variable:
From Sound.effects.echo import Echofilter
Similarly, this method imports Submodules: Mod:echo, and can be used directly with his: Func:echofilter function:
Echofilter (input, output, delay=0.7, atten=4)
Note that when you use the From package import item, the corresponding item can be either a sub-module (a child package) inside the packet, or a different name defined within the package, such as a function, class, or variable.
Import syntax first treats item as the name of a package definition and, if not found, attempts to import it as a module. If not found, congratulations, one: The Exc:importerror exception was thrown.
Conversely, if you use the Import form like import Item.subitem.subsubitem, except for the last item, it must be a package, and the last item can be a module or a package, but not the name of a class, function or variable.
Import from a package *
Imagine what would happen if we used the from sound.effects import *?
Python goes into the filesystem, finds all the sub-modules in the package, and imports them all in one.
Unfortunately, this approach does not work very well on the Windows platform because Windows is a case-insensitive system.
On such a platform, no one dares to vouch for a file called echo.py as a module: Mod:echo or: Mod:echo even: Mod:echo.
(For example, Windows 95 would hate to capitalize the first letter of each file) and the DOS 8+3 naming convention would make it more confusing to deal with long module names.
To solve this problem, only the trouble package author can provide an accurate index of the package.
The import statement follows the following rules: If the package definition file __init__.py has a list variable called __all__, then all the names in this list are imported as package content when using the From packages import *.
As the author of the package, don't forget to make sure that __all__ is updated after the update package. You said I would not do this, I will not use the import * This usage, OK, no problem, who let you be the boss. Here is an example where: file:sounds/effects/__init__.py contains the following code:
__all__ = ["echo", "surround", "reverse"]
This means that when you use the From sound.effects import * This usage, you will only import these three sub-modules inside the package.
If __all__ is really not defined, then when using the From sound.effects import * This syntax, it will not * Import Package: Any submodule in mod:sound.effects. He simply imports the package: Mod:sound.effects and all of the content defined inside it (possibly running: initialization code defined in file:__init__.py).
This will import all the names defined in the file:__init__.py: And he will not destroy all the explicitly specified modules that we have imported before this sentence. Look at this part of the code:
Import sound.effects.echoimport sound.effects.surroundfrom sound.effects Import *
In this example, before executing From...import, the package: the Echo and surround modules in the mod:sound.effects are imported into the current namespace. (Of course, if the definition of __all__ is even more no problem)
Generally we do not advocate using * This method to import modules, because this method often leads to reduced readability of the code. But it does save a lot of keystrokes, and some modules are designed to be imported only through specific methods.
Remember that this method is never wrong with the from package import Specific_submodule. In fact, this is also the recommended method. Unless the submodule you are importing is likely to have the same name as the submodule of the other package.
If the package in the structure is a child package (for example, in the case of a package: Mod:sound), and you want to import the sibling package (the same class), you have to import it using the import absolute path. For example, if the module: Mod:sound.filters.vocoder to use the package: Mod:sound.effects in the module: Mod:echo, you will write the from sound.effects import echo.
From. Import Echofrom. Import Formatsfrom. Filters Import Equalizer
Both implicit and explicit relative imports start with the current module. The name of the main module is always "__main__", and the main module of a Python application should always use absolute path references.
The package also provides an additional property: Attr:__path__. This is a list of directories in which each contained directory has a service for this package: file:__init__.py, you have to define it before the other: file:__init__.py is executed. This variable can be modified to affect the modules and sub-packages contained within the package.
This feature is not commonly used, and is generally used to extend the module inside the package.
Python3.5 Introductory Learning record-module