brief introduction
Python's interpretation environment is very easy to use, but if we need to write a large program, the interpretation environment is completely insufficient. At this time, we need to save the python program in a file. Usually this file is written in py.
For large applications, one file may not be enough. At this time, we need to reference other files in the file, so the file is called a module.
A module is a file that contains Python definitions and statements. The file name is the module name followed by the file suffix py . Inside the module, the module name can be passed through the global variable__ name__ get.
Module foundation
Or the previous example of fiborah sequence, we are in Fibo The function implementation is stored in the PY file:
def fib(n): # write Fibonacci series up to n a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() Copy code
After writing, we can import it in the Python interpretation environment:
>>> import fibo Copy code
Then use it directly:
>>> fibo.fib(1000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Copy code
Common functions can be assigned to a variable:
>>> fib = fibo.fib >>> fib(1000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Copy code
Or, when importing, we can name this module directly:
>>> import fibo as fib >>> fib.fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Copy code
Or import functions in the module:
>>> from fibo import fib as fibonacci >>> fibonacci(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Copy code
Each module has its own private symbol table, which is used as the global symbol table for all functions defined in the module. Therefore, the author of the module can use global variables within the module without worrying about unexpected conflicts with the user's global variables.
Execution module
We mentioned earlier that you can use import to import a module, and__ name__ The module name is saved in.
Like the main method in java, if we want to do some testing in the module, is there a writing method similar to the main method in java?
Let's take a look at an example:
if __name__ == "__main__": import sys fib(int(sys.argv[1])) Copy code
In the module, we need to make a judgment__ name__ Is it assigned as "_main_".
Let's execute this module as follows:
python fibo.py <arguments> Copy code
In the case of script execution, the module__ name__ Property is assigned to__ main__ , That's why it's written like this in the example.
See the execution effect:
$ python fibo.py 50 0 1 1 2 3 5 8 13 21 34 Copy code
If it is imported as a module, it will not be executed:
>>> import fibo >>> Copy code
Module search path
When importing a module using import, the interpreter will first look for the built-in module with that name. If it does not find it, the interpreter will start from sys Find the directory list given by the path variable.
sys. The initial directory of path includes:
- current directory
- Directory specified by PYTHONPATH
- Default values for installation
dir
To see what is defined in the module, use the dir function.
>>> a = [1, 2, 3, 4, 5] >>> import fibo >>> fib = fibo.fib >>> dir() ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] Copy code
The above example lists the contents defined in the current module, including variables, modules, functions, etc.
Note that dir() does not list the names of built-in functions and variables. If you want these, they are defined in the standard module builtins.
We can add parameters to dir to get the contents of a specific module:
>>> import builtins >>> dir(builtins) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] Copy code
package
java has the concept of package, which is used to isolate program code. Similarly, there are packages in Python.
Let's look at an example of a package in Python:
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ... filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py ... Copy code
We have defined four packages above, which are sound and sound formats, sound. effects, sound. filters.
Note that if it is a package, it must contain__ init__.py file.
__ init__.py can be an empty file, or it can execute the initialization code or settings of the package__ all__ Variable.
When importing, python will be in sys Search the path for the package.
There are many ways to import packages. We can import a single module:
import sound.effects.echo Copy code
However, after such import, the full name must be loaded when using:
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4) Copy code
If you do not want to load the full name, you can import it as follows:
from sound.effects import echo Copy code
Then it can be used as follows:
echo.echofilter(input, output, delay=0.7, atten=4) Copy code
You can also directly import the methods in the module:
from sound.effects.echo import echofilter Copy code
Then use this:
echofilter(input, output, delay=0.7, atten=4) Copy code
If there are many sub packages in a package, we may want to use * to import at one time:
from sound.effects import * Copy code
So how to control which sub package of effects will be imported?
We can__ init__.py__ all__ List of packages to be exported, as shown below:
__all__ = ["echo", "surround", "reverse"] Copy code
So from sound Effects import * will import the three named sub modules of the sound package.
If not defined__ all__, from sound. The effects import * statement is not from the package sound Import all sub modules into the current namespace in effects; It will only import the package sound effects.
Relative path of package
Import can specify relative paths, which we use To represent the current package, use To represent the parent package.
As follows:
from . import echo from .. import formats from ..filters import equalizer