10_1_ modules and packages

During development of a computer program, with the program code write more and more, in a file, the code will become longer and more difficult to maintain.

In order to write code maintainable, we put a lot of function groups, which are placed in a separate file, so each file contains the code is relatively small, many programming languages have adopted this way of organizing code. In Python, a .pyfile is called a module (Module1) .

which is:

  • We included variables defined functions and file to ".py" as a suffix.
  • Module can be referenced by other programs, to use the functions or data module.

Advantage of the module:

  • 1. improve code maintainability
  • 2. improve the reusability of code
  • 3. The functional module can import many (standard library modules, custom modules, third party modules)
  • 4. To avoid a repeat variable name

    Import module

    Python simple form of the method introduced in three main modules:

import 模块名
import模块名 as 新名称
from 模块名 import 函数名

the difference:

  • import 模块名withimport 模块名 as 新名称

    • Entire module will be introduced;
    • If you need to use one of these functions, you must call the function with "Module name Function name ()" form. (Usually this method, is more conducive to enhance the readability of the code, priority would be the use of that method)
    • import 模块名 as 新名称To rename imported modules, so that the name is simple and easy to use.
  • from 模块名 import 函数名

    • Introducing only a function module, rather than introducing the whole module.
    • You can call the function directly using the function name, no need to add "module name." On its front.

    If the program statement very much, we do not recommend using "from the module name import function" in this way, because this way the function is called, we call the function directly using the function name, when very large program statement, we call a lot of modules after the function name may result in duplicate names, causing the error, and the "module name function name" approach will prevent this from happening.

example:

Python module with built-in calendar for example, the name defines some calendar format calendar.py, inside. As long as this imported using the import command module, the module can use the calendar.

1, 3, 5, 7, 8, 10, 12 ---> 31 days

Except for February, 30 days

February: 29 leap year, leap year 28

  • import ...
>>> import calendar # 导入calendar模块
>>> print(calendar.month(2019,4)) # 调用用模块中的month()函数 
     April 2019
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

>>> calendar.isleap(2019)
False
  • import ... as ...
>>> import calendar as cal
>>> print(cal.month(2019, 4))
     April 2019
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

>>> cal.isleap(2019)
False
  • from ... import ...
>>> from calendar import month
>>> print(month(2019, 4))
     April 2019
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

>>> isleap(2019)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'isleap' is not defined
>>>

注意,

- import 语句的模块顺序:

We recommend that all imported modules in the beginning of Python modules. Further preferably in this order:

  • Python standard library modules
  • Python third-party modules
  • Custom application modules

Then use a blank line dividing these three modules import statements. This will ensure that the module uses a fixed habit import, help to reduce the number of import statements for each module needed. Other tips please refer to the "Python Style Guide" (Python's Style Guide), PEP8.

- 限制使用 "from module import *"

In practice, we believe that "from module import *" is not a good programming style, because it is "contaminated" the current namespace, and is likely to override the current namespace existing name; but if a lot of modules have to be frequently accessed variable or module name is very long, it would be a good way convenient.
We only recommend the use of such methods in both cases, a situation is: the target module attributes very much, repeatedly type the name of the module is very convenient, for example Tkinter (Python / Tk) and NumPy (Numeric Python) module, possibly there socket module. Another case is the interactive interpreter, because it reduces the number of inputs.

View path to the module:

模块名.__file__

>>> calendar.__file__
'D:\\Anaconda3\\lib\\calendar.py'
>>>

Custom Modules

The so-called stand-alone program module is our custom to write their own modules (.py files), can be either a solution to a problem may also contain multiple functions.

Name of the custom module is the name we write Python programs.

Here we give you an example:

In the previous course, we have contacted Fibonacci number (the Fibonacci), except for the first and second number, any number can be obtained by adding by the first two numbers:

1, 1, 2, 3, 5, 8,13, 21, 34, ...

Now we create a file called fibo.py, as follows:

 # 程序名称为fibo.py
# 斐波那契数列模块
def fib_01(n):          # 输出最大数小于n的斐波那契数列
    i, j = 0, 1
    while j < n:
        print(j, end = ' ')
        i, j = j, i + j
    print()
    
def fib_02(n):          # 以列表的形式输出最大数小于n的斐波那契数列
    result = []         
    i, j = 0, 1
    while j < n:
        result.append(j)
        i, j = j, i + j
    return result

Cmd to open a command window in the current directory. Enter the Python interpreter environment, and then:

>>> import fibo

Enter, if there is no error, Congratulations, you have successfully imported this module a. This does not import the function name defined in fibo, only enter the module name fibo. Using the module name, which we can access functions:

>>> import fibo        # 导入模块
>>> fibo.fib_01(100)    # 调用导入模块的函数
1 1 2 3 5 8 13 21 34 55 89
>>> fibo.fib_02(100)    # 调用导入模块的函数
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>

If Next, we will repeatedly use fib_01 function, we can do this:

>>> fib = fibo.fib_01
>>> fib(100)
1 1 2 3 5 8 13 21 34 55 89
>>> fib(200)
1 1 2 3 5 8 13 21 34 55 89 144
>>> fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>>

reload()

reload () built-in function may be reintroduced into a module has been introduced. Its syntax is as follows:

import importlib
importlib.reload(module)

module that you want to re-import the module. Use reload () when there is some standard. First, all modules must be introduced (not using from-import), and it must be successfully introduced. Further parameters reload () function must be a module comprising a module string itself, rather than the name. That must be similar to reload (sys) rather than reload ( 'sys').
Module code is executed at the time of import, but executed only once, after the implementation of the import statement does not execute the code again, just bind the module name. Different reload () function.

Module search path

In front of us when you import the module is required to open a command window in the path fibo.py where, and why?

In general, Python interpreter when you run the program, before the program will automatically add the current directory where the path to the next sys.path list, and then, first search module in the current path. On Windows systems, the default module search path for the prime Python installation directory and install several sub-directory under the file folder, we can see in the following ways python interpreter environment:

>>> import sys          # 导入sys模块
>>> print(sys.path)       # 输出当前的模块搜索路径,以列表形式显示
['','D:\\Python36\\python36.zip','D:\\Python36\\DLLs','D:\\Python36\\lib', 'D:\\Python36', 'D:\\
python36\\lib\\site-packages']
>>>

If we do not want to fibo.py file directory path start cmd command window can import fibo.py module, we can use:

sys.path.append(AddPath)

Add fibo.py temporary file directory path.

Now, open cmd:

C:\Users\Administrator>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append('E:\\python')
>>> import fibo
>>> fibo.fib_01(100)
1 1 2 3 5 8 13 21 34 55 89
>>>

Guess you like

Origin www.cnblogs.com/geoffreygao/p/12161170.html