Explain Python modules, packages and libraries in detail

1. Module

Python module is a file containing Python definitions and statements (that is, a script file ending in. py);
The file name is the module name and the file suffix is py;
Within a module, the module name can be__ name__ Method.

Definition module

Define a module Fibo, that is, create a Fibo Py file# fibo.py

# Fibonacci numbers module

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()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Import module

python is used to putting all the "import" statements at the beginning of the script and calling them globally.

>>> import fibo#Import module fibo
>>> fibo.__name__#__ name__ Method to obtain the module name of the module fibo
'fibo'

Calling functions in modules

Method 1 module name Function name

>>> import fibo
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Method 2 from module name import function name 1 Function name 2

>>> from fibo import fib,fib2#Multiple function names are separated by commas
>>> fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Method 3 from module name import*

*Represents all functions in the module, which will lead to poor code readability (not recommended).

>>> from fibo import *
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Alias the module

import module name as alias

>>> import fibo as fb
>>> fb.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Alias the function in the module

from module name import function name as function alias

>>> from fibo import fib2 as fb2
>>> fb2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Execute the module in a scripted manner

fibo.py

# Fibonacci numbers module
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()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

if __name__ == "__main__":
        print("Now the module is executed as a script!")
        print(("here__name__ == %s"%(__name__)))#At this point, the module's__ name__ For__ main__
        import sys
        result = fib2(int(sys.argv[1]))
        print(result)

python fibo.py 100#if name == "__main__": Then the code block is executed (commonly used for testing)
Now the module is executed as a script!
At this time__ name__ == main
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

__ name__ How do you understand

__ name__ Is a global variable that stores the name of the module;
When the module is called by other modules__ name__= Module name, for Fibo py,__ name__="fibo";
When the module is treated as an execution script__ name__ For__ main__ ( A module’s name is set equal to '__main__' when read from standard input, a script, or from an interactive prompt).
For Fibo Py, if the terminal executes Python Fibo py 100 ,if name == "__main__": The following code will be executed; If you execute import fibo in another module, if name = = "_main_": The following code will not be executed.

import fibo#if name == "__main__": After that, the code block was not executed\

View attributes in the module: dir function

>>> import fibo
>>> dir(fibo)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'fib', 'fib2']

With__ The attributes at the beginning and end are python's built-in attributes;
'fib', 'fib2' are user-defined attributes.

The import module is sys How do you understand path

sys.path collects all search paths of python module. You can add your own search path (sys.path.append('yourpath '). For example:

#test.py
#!/usr/bin/python
import sys
sys.path.append('~/biosoft/')
print(sys.path)
> python test.py
['/home/pylearning', 
 '/home/software/anaconda3/lib/python37.zip',
 '/home/software/anaconda3/lib/python3.7', 
 '/home/.local/lib/python3.7/site-packages', 
'/home/software/anaconda3/lib/python3.7/site-packages',
'~/biosoft/'
]

When any python program executes, it will search the path of its imported module, and first search the path of the built-in module;
Then search sys Path collection path, sys The paths in path are as follows:

The ['home / home home / pylearing' '' '' '' \\\\\\ '' '' '' '' '' '' '' '' '' '' '' '' '' \\\\\\\\\\\\\\\\\\\]

2. Package (Library)

Create a package

The sound package contains three sub packages: formats, effects and filters.

sound/                          #Top level package (sound)
      __init__.py              #The file can be empty. sound will be regarded as a package instead of a directory only when the file exists
      formats/                  #Subpackage
              __init__.py     #As above, formats will be treated as a package instead of a directory only when the file exists
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              haha.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
             haha.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

In the bag__ init__. Role of Py file
Add to directory only__ init__.py file, the directory will be regarded as a package instead of a directory;
__ init__.py can be empty;
__ init__.py can be set__ all__ Variable, which mainly affects the import of packages

  • For the above sound package, sound/filters/__init__.py__ all__ == ["equalizer", "vocoder"], from sound The karaoke module will not be imported when filters import *.

Import a single module from a package

Import the echo module in the sub package effects of the sound package

Method 1

import sound.effects.echo must use its full name when referring to it, sound effects. echo(xxx).

Method 2

from sound.effects import echo reference method, echo(xxx)

Import all modules from package

from sound.effects import * reference method, echo(xx)

Keywords: Python

Added by bughunter2 on Wed, 26 Jan 2022 11:22:02 +0200