Chapter 4
If you exit the python interpreter and re-enter, the methods and variables you have defined will disappear. Therefore, if you want to write a long program, you 'd better use a text editor to prepare input for the interpreter and run the program using files as input. This is a well-known script. If your program is more powerful and responsible, you may want to divide it into several files for convenience of maintenance. You may want to use the convenience method you have written in the file without copying it to every program.
To support this function, Python provides a way to place these definitions in a file and use them in interactive instances of scripts or interpreters. In python, such a file is called a module. The definitions in the module can be imported directly to other modules or main modules. (You enter the set of variables in execution script or computing mode at the top layer)
A module is a file that contains python definitions and statements. The file name is composed of the module name and suffix. py. In a module, the module name (which can be used as a string) is a variable used as the value of the global variable _ name. For example, use your favorite text editor to create a file named fibo. py in the current directory. The file content is as follows:
Def fib (n): # write Fibonacci series up to n
A, B = 0, 1
While B <n:
Print (B, end = '')
A, B = B, a + B
Print ()
Def fib2 (n): # return Fibonacci series up to n
Result = []
A, B = 0, 1
While B <n:
Result. append (B)
A, B = B, a + B
Return result
Now go to the python interpreter and run the following command to import the module.
>>> Import fibo
It is not allowed to enter the method name defined directly in the current symbol table. You can only enter the module named "fibo. You can use the module name to access the method.
>>> Fiber. fib (1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
>>> Fig (100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> Fibo. _ name __
'Pipeline'
39
If you use this method, you often assign it to a local name.
>>> Fib = maid
>>> Fib (500)
1 1 2 3 5 8 13 21 34 55 89 144 233