tags: Python Development language rear end
Reprinted
In the previous section, we have used many modules (such as String, Sys, OS, etc.), which we can use many "current" functions to implement the desired features by importing these modules into the program.
So, what is the module, what is the inside of the module look like, can the module can be customized? This chapter will lead the reader to learn more about the modules in Python, such as such questions, this chapter will give you all one by one.
In addition, this chapter will explain the package in Python, which is also a module, which is a tool for effective management modules.
Python Provide powerful module support, mainly, not only the Python Standard Library contains a large number of modules (called standard modules), but also a large number of third-party modules, developers you can also develop custom modules. These powerful modules can greatly improve the development efficiency of developers.
So, what is the module refers to? Module, English is Modules, as for the module, you can summarize: The module is a Python program. In other words, any Python program can be used as a module, including all Python programs written in the previous chapter, can be used as a module.
The module can be compared to a box of building blocks, which can spell all a variety of topics, which are different from the functions described above, and a function is only equivalent to a building block, and a module (.py file) can contain multiple functions, That is, there are a lot of building blocks. The relationship between modules and functions is shown in Figure 1.

Figure 1 Relationship between modules and functions
After learning, readers have been able to write Python code into a file, but with the complicacy of the program, the program volume will continue to be large. In order to facilitate maintenance, it is usually divided into multiple files (modules), so Not only can you improve the maintenanceability of your code, but also improve the reusability of your code.
The reusability of the code is manifested when a module is written, as long as the programming process needs to use a feature in the module (by variables, functions, classes implementation), no need to do repetitive writing work, direct in the program This feature can be used in this module.
The package has been packaged, and many of the structures with packaging characteristics are also introduced, such as:
The modules described in this section can be understood as being a higher level package, ie, write code that can implement a particular function in the same .py file, and use it as a separate module, which can be convenient Other programs or scripts are imported and used, but also effectively avoid conflicts of function names and variable names.
For a simple example, under a directory (desktop can also) create a hello.py file, the code contains as follows:
def say ():
print("Hello,World!")
Under the same directory, create a Say.py file, the code contains as follows:
# Introduce this file through the Import keyword
import hello
hello.say()
Run the SAY.PY file whose output is:
Hello,World!
The reader may notice that the SAY () function originally available in the Hello.py file is used in the Say.py file. Hello.py is a custom module (related to custom modules, The subsequent chapter will explain the detailed explanation), we only need to import the Hellp.py module into the Say.py file, you can use the resources in the module directly in the Say.py file.
At the same time, when the SAY () function in the module is called, the syntax format used is "Module Name. Function", because, relative to the SAY.PY file, the code in the Hello.py file self-into a namespace Therefore, when the function in other modules is called, it is necessary to clearly indicate the source of the function, otherwise the Python interpreter will report an error.
use Python When programming, some features do not have to implement themselves, and can use the Python existing standard libraries or third-party libraries from others. For example, in the previous chapter, we use some mathematical functions, such as cosine functions, COS (), absolute value functions Fabs (), etc., in the Math (or CMATH) module in the Python Standard Library, only need to put this module Import to the current program, you can use it directly.
In the previous chapter, I have seen the syntax of the import module using the Import, but in actually IMPORT has more detailed usage, mainly two types:
Import module 1 [AS alias 1], module name 2 [AS alias 2], ...: Use this grammar format Import statement to import all members of the specified module (including variables, functions, classes, etc.). Not only that, but when you need to use members in the module, you need to use this module name (or alias) as a prefix, otherwise the Python interpreter will report an error.From module name Import member name 1 [AS alias 1], member name 2 [as alias 2], ...: Using this grammar format IMPORT statement, only the members specified in the module are imported, not all members. At the same time, when using the member in the program, there is no need to add any prefixes, directly use the member name (or alias).Note that the part of [] can be used, can be used, or it can be omitted.
Among them, the second IMPORT statement can also import all members in the specified module, which is used with the Form module name import *, but this method is not recommended, and the specific cause will be described in detail.
The following program uses the simplest syntax imported into the entire module to import the specified module:
# Import SYS Over Module
import sys
# Use the SYS module name as a prefix to access members in the module
print(sys.argv[0])
The second line of code is imported into the SYS module using the simplest manner, so when the member in the SYS module is used in the program, the module name must be added as a prefix.
Run the above program, you can see the following output (the Argv variable under the SYS module is used to obtain command line parameters running the Python program, where argv [0] is used to get the store path of the current Python program):
C:\Users\mengma\Desktop\hello.py
When importing the entire module, you can specify an alias for the module. For example, as follows:
# Import the entire module of SYS and specify an alias for s
import sys as s
# Use the S module alias as a prefix to access members in the module
print(s.argv[0])
The second line of code specifies the alias S when importing the SYS module, so when the member in the SYS module is used in the program, the module alias S must be added as a prefix. Run the program, you can see the following output:
C:\Users\mengma\Desktop\hello.py
You can also import multiple modules at once, and multiple modules can be separated by commas. For example, as follows:
# Import SYS, OS two modules
import sys,os
# Use the module name as a prefix to access members in the module
print(sys.argv[0])
# os module SEP variable represents path separator on the platform
print(os.sep)
The second line of code is imported into the SYS and OS modules at a time, so the program uses the members within the two modules of the OS, as long as the SYS, the OS module name is used as a prefix. Run the program on the Windows platform, you can see the following output (the SEP variable of the OS module represents the path separator on the platform):
C:\Users\mengma\Desktop\hello.py
\
While importing multiple modules, you can specify an alias for modules, such as the following procedures:
# Import SYS, OS two modules, and specify an alias S for SYS, specify an alias OS OS O
import sys as s,os as o
# Using module alias as a prefix to access members in the module
print(s.argv[0])
print(o.sep)
The second line of code is imported at a time, and the SYS and OS modules are imported, and they specify alcohols for them to S, O, so the program can use S, O two members in the two modules. Run the program on the Windows platform, you can see the following output:
C:\Users\mengma\Desktop\hello.py
\
The following programs use from ... import simple syntax to import the specified member:
# s
from sys import argv
# Use the grammar of import members, directly use member name access
print(argv[0])
The second line code introduces the Argv member in the SYS module so that you can use the Argv member directly in the program without having to use any prefix. Run the program, you can see the following output:
C:\Users\mengma\Desktop\hello.py
When importing module members, you can specify an alias for members, such as the following procedures:
# Import the Argv member of the SYS module and specify an alias V.
from sys import argv as v
# Use the grammar of import members (and specify alias), directly using members' alias access
print(v[0])
The second line code introduces the Argv member in the SYS module and specifies the alias V for the member, so that you can use the ARGV member in the program, no prefix. Run the program, you can see the following output:
C:\Users\mengma\Desktop\hello.py
When Form ... import import module member, support multiple members, such as the following procedures:
# Import the Argv of the SYS module, Winver member
from sys import argv, winver
# Use the grammar of import members, directly use member name access
print(argv[0])
print(winver)
The second line of code is imported into the Argv, Winver member in the SYS module, so that you can use the Argv, Winver two members directly in the program without any prefix. When running the program, you can see the following output (SYS's Winver member logs the version number of the Python):
C:\Users\mengma\Desktop\hello.py
3.6
When you import multiple module members at a time, you can also specify an alias, and use the AS keyword to specify an alias for members, such as the following procedure:
# Import the Argv, Winver member of the SYS module, and specify an alias V, WV
from sys import argv as v, winver as wv
# Use the grammar of import members (and specify alias), directly using members' alias access
print(v[0])
print(wv)
The second line of code is imported into the Argv, Winver member in the SYS module, and specifies the alias V, WV, which can use Argv, Winver members, and no prefixes can be used through V and WV two alias, respectively. . Run the program, you can see the following output:
C:\Users\mengma\Desktop\hello.py
3.6
When using the from ... import syntax, you can import all members in the specified module (this mode is not recommended) once, for example, as follows:
# Import all members in the SYS chess block
from sys import *
# Use the grammar of import members, directly use the member's alias access
print(argv[0])
print(winver)
The above code imports all members in the SYS module once so that programs can use all members of the module through member name. The output result of the program and the output result of the previous program are identical.
It should be noted that "from module import" syntax is generally not recommended to import all members of the specified module because it has potential risks. For example, all members in Module1 and Module2 are imported, if there is a foo () function in these two modules, then the following code is executed in the program:
foo()
Is the foo () function called above or the Module1 module in the module2 module? Therefore, this imported specified module is risky.
But if you replace the following two types of import:
import module1
import module2 as m2
Next, the FOO () function in these two modules is called very clearly. The program can use the following code:
# Using the module Module1 module name as a prefix call foo () function
module1.foo()
# Use module alias for module2 as a prefix foo () function
m2.foo()
Or use from ... import statement is also possible:
# Import the Foo member in Module1, and specify its aliased as foo1
from module1 import foo as fool
# Import the Foo member in Module2, and specify its alias to foo2
from module2 import foo as foo2
At this point, the FOO function in the two modules in the two modules in the two modules in the other is very clear, and the FOO () function in the two modules is clearly called:
FOO1 () # Call the foo () function in Module1
Foo2 () # Call the foo () function in Module2
So far, readers have mastered importsPython The standard library and the method of using its member (mainly a function), the problem to be solved is, how to customize a module?
In the previous chapter, the Python module is a Python program. In other words, as long as it is a Python program, it can be imported as a module. For example, a simple module is defined below (written in a demo.py file):
Name = "Python Tutorial"
add = "http://c.biancheng.net/python"
print(name,add)
def say():
Print ("Life is short, I learn Python!")
class CLanguage:
def __init__(self,name,add):
self.name = name
self.add = add
def say(self):
print(self.name,self.add)
It can be seen that we placed a variable (Name and add), function (SAY ()) and a Clanguage class in the demo.py file, which can be used as a template.
But in general, in order to verify the correctness of the code in the template, we often need to design a test code for its design, for example:
say()
Clangs = Clanguage, "http://c.biancheng.net")
clangs.say()
Run the demo.py file, its execution result is:
Python tutorial http://c.biancheng.net/python
Life is short, I learn Python!
C language in Chinese http://c.biancheng.net
The execution result of the program in the template can be concluded that the functions and classes contained in the template file are working properly.
On this basis, we can create a Test.py file and use the demo.py template file in this file, and import demo.py with the import statement:
import demo
Note that although the DEMO template file is full of demo.py, only the name of the template file is only required when using the Import statement.
At this point, if the Test.py file is directly run, its execution result is:
Python tutorial http://c.biancheng.net/python
Life is short, I learn Python!
C language in Chinese http://c.biancheng.net
It can be seen that when the test.py file is executed, it will also execute the programs used to test in demo.py, which is obviously not what we want. The normal effect should be that the test code will be executed only when the template file is run directly;
To achieve this effect, you can use Python built-inname variable. When you run a module directly, the value of the Name variable ismainAnd when the module is imported into other programs and run the program, in the modulename The value of the variable becomes the module name. Therefore, if you want the test function to execute when you run the module file directly, you can add judgment when calling the test function, that isname ==‘main'Call the test function when you are.
Therefore, we can modify the test code in the Demo.py template file:
if __name__ == '__main__':
say()
Clangs = Clanguage, "http://c.biancheng.net")
clangs.say()
This way, when we run the DEMO.PY template file, its execution result is unchanged; when the Test.py file is run, its execution results are:
Python tutorial http://c.biancheng.net/python
Obviously, the output statement in the template file is only executed here, and the test code is not executed.
We know that when defining a function or class, we can add a document to it to make it clear that the user knows the function or class. Custom modules are no exception.
Add a document to the custom module, and the function or class adding method, you only need to define a string in the position of the module. For example, add a documentation for the Demo.py template file:
‘’’
The following contents are included in the DEMO module:
Name string variable: initial value is "Python Tutorial"
Add string variable: initial value is "http://c.biancheng.net/python"
Say () function
Clanguage Class: Contains Name and ADD attributes and Say () methods.
‘’’
On this basis, we can pass templatesdocAttributes to access the template documentation. For example, add the following code in the Test.py file:
import demo
print(demo.__doc__)
The program operation results are:
Python tutorial http://c.biancheng.net/python
The following contents are included in the DEMO module:
Name string variable: initial value is "Python Tutorial"
Add string variable: initial value is "http://c.biancheng.net/python"
Say () function
Clanguage Class: Contains Name and ADD attributes and Say () methods.
As mentioned earlier, in fact, the module is a code file, so its file name is required to meet the naming rules of the operating system.
This may encounter a problem, which allows the file name in the operating system to include spaces, that is, the module file can be named similar "A B". However, this is contradictory and in other words, Python is spaced to isolate different elements in a line of statements. If there is a space in the module name, IMPORT cannot be used again.
For example, we customize a module and name "demo text.py", which only contains the following output statement:
Pure text copy
Print ("C Language Chinese Network")
If in other files, it is still introduced in the Import statement, the Python interpreter will report the SYNTAXERROR error:
>>>import demo text
SyntaxError: invalid syntax
Not only that, if the module name begins with a number, it is not possible to use the import statement to import normally. For example, change the "Demo Text" module file name to "1Demo" and use import attempt to import, and will also report the SyntaxError error:
>>> import 1demo
SyntaxError: invalid syntax
For the above two cases, if the module contains spaces or beginning with numbers, Python is required.import() Built-in function introduction module. For example, when the module is named "DEMO TEXT", the introduction method is as follows:
__import__("demo text")
The result of the operation is:
C language
Similarly, if the module is named "1Demo", the introduction method is as follows:
__import__("1demo")
The result of the operation is:
C language
Pay attention, useimport() When the function introduces the module name, the module name is introduced in a string, otherwise the SyntaxError error will be reported.
The previous section has been explained in the module and its usage, I believe that many readers have begun to try to read the code of others (usually reading the code written by people than yourself, will make their own technical level rapidly). However, when reading the custom modules written by others, you often see the following row judgment statement:
if __name__ == '__main__':
What is the role of this line of code? This section explains the following roles.
In general, when we write a custom module, you will write a test code, check whether each function in some modules can run successfully. For example, create a Candf.py file and write the following code:
'''
Celsius and Fahrenheit mutual conversion module
'''
def c2f(cel):
fah = cel * 1.8 + 32
return fah
def f2c(fah):
cel = (fah - 32) / 1.8
return cel
def test():
Print ("Test Data: 0 degrees Celsius =% .2F Fahrenheit"% C2F (0))
Print ("Test Data: 0 Fahrenheit =% .2F Celsius"% F2C (0))
test()
Run this module file separately, you can see the following results:
Test data: 0 degrees Celsius = 32.00 degrees
Test data: 0 Fahrenheit = -17.78 degrees Celsius
On the basis of the Candf.py module file, create a demo.py file in the same directory and write the following code:
import candf
Print ("32 degrees Celsius =% .2F Fahrenheit"% CANDF.C2F (32))
Print ("99 Fahrenheit =% .2F Celsius"% CANDF.F2C (99))
Run the Demo.py file, the results are as follows:
Test data: 0 degrees Celsius = 32.00 degrees
Test data: 0 Fahrenheit = -17.78 degrees Celsius
32 degrees Celsius = 89.60 Fahrenheit
99 Fahrenheit = 37.22 degrees Celsius
It can be seen that the Python interpreter runs a test code in the module (CANDF.PY), which is not what we want. The key to avoiding this situation is that you want the Python interpreter to know that the extent to which the current to run is the module file itself, or other programs of the import module.
In order to achieve this, you need to use the Python built-in system variable.nameIt is used to identify the module name of the module. For example, in the Demo.py program file, add the following code:
print(__name__)
print(candf.__name__)
Its operation results are:
__main__
candf
It can be seen that the program currently runs,name ValuemainAnd import into the module in the current program,name Value is your own module name.
therefore,if __name__ == '__main__': The role is to ensure that this expression can only be set up if only the module is run separately, and can enter this judgment syntax, execute the test code; When running other programs, the test code in the judgment statement will not be executed.
Many beginners often encounter such problems, that is, customizePython After the template, the Python interpreter is incorrect with the IMPORT (or from ... import) statement in other files:
ModulenotFounderror: no module named 'Module name
It means that Python can't find this module name. What is the cause of this? To solve this problem, the reader must first figure out the process of the Python interpreter lookup module file.
Typically, when importing modules with an Import statement, Python looks for the specified module file in order:
All the above-mentioned directories are saved in the Sys.Path variable of the standard module SYS, and we can see all directories that specify the program file support lookup. In other words, if the module to be imported is not stored in the directory displayed in sys.path, the Python interpreter will throw the moduleNotFoundError when the program is imported and running the program.
There are three ways to solve "Python find the specified module", namely:
However, before detailed introduction, in order to easily explain it, this section uses the previous chapter established Hello.py custom module file (D: \ python_module \ hello.py) and Say.py program files (C: \ users \ mengma \ desktop \ SAY.PY, on the desktop), their respective code is as follows:
#hello.pydef say (): print("Hello,World!")#say.pyimport hellohello.say()
Obviously, hello.py files and SAY.py files are not in the same directory, run the SAY.PY file, and its run results are:
Traceback (most recent call last):
File “C:\Users\mengma\Desktop\say.py”, line 1, in
import hello
ModuleNotFoundError: No module named ‘hello’
It can be seen that the Python interpreter throws the ModulenotFoundError exception. Next, this problem is solved with the above three methods.
The storage location of the module file can be temporarily added to the sys.path variable, i.e., add D: \ python_module to sys.path, add the following code at the beginning of Say.py:
import syssys.path.append('D:\\python_module')
Note: In the Add full path, '' in the path needs to use \ to perform escape, otherwise the syntax error can be caused. Run the SAY.PY file again, the results are as follows:
Hello,World!
It can be seen that the program is successful. On this basis, we output the value of the sys.path variable in the Say.py file, it will result in the following results:
[‘C:\Users\mengma\Desktop’, ‘D:\python3.6\Lib\idlelib’, ‘D:\python3.6\python36.zip’, ‘D:\python3.6\DLLs’, ‘D:\python3.6\lib’, ‘D:\python3.6’, ‘C:\Users\mengma\AppData\Roaming\Python\Python36\site-packages’, ‘D:\python3.6\lib\site-packages’, ‘D:\python3.6\lib\site-packages\win32’, ‘D:\python3.6\lib\site-packages\win32\lib’, ‘D:\python3.6\lib\site-packages\Pythonwin’, ‘D:\python_module’]
In this output, the red part is a temporary addition of the stored path. It should be noted that the directory added by this method can only be valid in the window of executing the current file, the window is invalidated after the window is closed.
If you want to install certain versatile modules, such as modules, matrix computing modules, matrix computing modules, modules supported by the graphical interface, etc., which belong to the module that extends to Python itself, which should be installed directly in Python, To be shared by all programs, at this time, the Python default module load path can be loaded.
The Python program default module load path is saved in the sys.path variable, so we can first take a look at the default load path saved in sys.path in the Say.py program file, and output sys.path to the Say.py file. Value, as shown below:
[‘C:\Users\mengma\Desktop’, ‘D:\python3.6\Lib\idlelib’, ‘D:\python3.6\python36.zip’, ‘D:\python3.6\DLLs’, ‘D:\python3.6\lib’, ‘D:\python3.6’, ‘C:\Users\mengma\AppData\Roaming\Python\Python36\site-packages’, ‘D:\python3.6\lib\site-packages’, ‘D:\python3.6\lib\site-packages\win32’, ‘D:\python3.6\lib\site-packages\win32\lib’, ‘D:\python3.6\lib\site-packages\Pythonwin’]
In the above operational results, all paths listed are Python's default module load path, but in general, we will add Python's extension modules by default.lib\site-packages Under the path, it is specifically used to store the Python extension modules and packages.
So, we can directly add our good hello.py files.lib\site-packages Under the path, it is equivalent to extending a Hello module for Python, so that any Python program can use the module.
After the movement works, run the SAY.PY file again, you can see the result of successful run:
Hello,World!
The value of the PythonPath environment variable (referred to as Path variable) is a collection of multiple paths, and the Python interpreter performs a search by using the path contained in Path until the module you want to load is found. Of course, if it is still not found, Python reported ModulenOTFoundError.
Due to different platforms, setting the PATH environment variable is not the same, so the three platforms of the most Windows, Linux, Mac OS X are used, and the reader describes how to set the PATH environment variable.
First, find the "computer" on the desktop (or my computer), and click the right mouse button, click Properties. The Control Panel \ All Control Panel Items \ System window is displayed, click the Advanced System Settings menu in the left bar left, the System Properties dialog box appears, as shown in Figure 1.

Figure 1 System Properties dialog
As shown in Figure 1, click the "Environment Variable" button, and the dialog shown in Figure 2 will pop up:

Figure 2 Environment Variables Dialog
As shown in Figure 2, the setting of the PATH environment variable can be completed by this dialog. It should be noted that the dialog is divided into a top and bottom portion, wherein the "User Variable" portion above is used to set the environment variable of the current user, the following "System Variable" section is used to set the environment variable of the entire system.
Typically, it is recommended that you set up setting the user's path variable because this setting is only valid for users of the current login system, and if the system's PATH variable is modified, all users are valid.
For ordinary users, the effect of setting user Path variables and system PATH variables is the same, but when Python uses the PATH variable, then follow the path to the system PATH variable, then follow the path to the user PATH variable.
Here we choose to set the PATH variable of the current user. Click the "New" button in the user variable, the system will pop up the dialog shown in Figure 3.

Figure 3 New PythonPath environment variable
Among them, enter PythonPath in the "Variable Name" text box, indicating that the environment variable named PythonPath will be established; enter the "Variable" text box input.;d:\python_ module. Note that this actually includes two paths (in a semicolon; as a separator):
d:\python_ moduleWhen running the Python program, Python will be available fromd:\python_ module Loading modules.Then click "OK" to successfully set the PATH environment variable. At this point, we only need to move the module file to the same directory as the file that introduces the module, or moves tod:\python_ module Under the path, the module can be successfully loaded.
Start Linux's terminal window, enter the current user's HOME path, then enter the following command under the HOME path:
ls - a
This command lists all files under the current path, including hidden files. The environment variable of the Linux platform is set by the .bash_profile file, open the file with a form of format editor, add a PythonPath environment variable in this file. That is, the next line is increased for this document:
# Set the python path environment variable
PYTHONPATH=.:/home/mengma/python_module
Linux is different from the Windows platform, and multiple paths are different (:) as separators, so two paths are also set, point (.) Represents the current path, and a path is/home/mengma/python_module(Mengma is the login of the Linux system).
After completing the setting of the PythonPath variable, the statement that exports the PythonPath variable is added at the last addition of the .bash_profile file.
# Export PythonPath environment variables
export PYTHONPATH
Re-log in to the Linux platform, or execute the following command:
source.bash_profile
These two ways are to run the file, enabling the PythonPath variable value set in the file to take effect.
After successfully set the above environment variable, then just put the previously defined modules (Python program) in the same path as the currently running Python program (or put it/home/mengma/python_module Under the path), the module can be successfully loaded.
Setting the environment variables on Mac OS X is roughly the same as Linux (because Mac OS X itself is also a UNIX system). Start the terminal window (command line interface) of the Mac OS X, enter the current user's Home path, then enter the following command under the Home path:
ls -a
This command lists all files under the current path, including hidden files. The environment variable of the Mac OS X platform can also be set by, the Bash_Profile file is set, and the file is opened with a form of format editor to add a PythonPath environment variable in that file. That is, the next line is increased for this document:
# Set the python path environment
PYTHONPATH=.:/Users/mengma/python_module
There are also two paths between multiple paths of Mac OS X as separators./Users/mengma/python_module(Memgma is the author's login in the Mac OS X system).
After completing the setting of the PythonPath variable, the statement that exports the PythonPath variable is added at the last addition of the .bash_profile file.
# Export Python path environment variable
export PYTHONPATH
Reply to the Mac OS X system, or execute the following command:
source.bash_profile
These two ways are to run the file, enabling the PythonPath variable value set in the file to take effect.
After successfully set the above environment variable, then just put the previously defined modules (Python program) in the same path as the currently running Python program (or put itUsers/mengma/python_module Under the path), the module can be successfully loaded.
To help you better understand the import module, define a new module below, which is relatively simple, so no longer write test code. The module code is as follows (written in the fk_module.py file):
'A simple test module: fk_module'
print("this is fk_module")
name = 'fkit'
def hello():
print("Hello, Python")
Next, the following procedure is defined under the same path:
import fk_module
print("================")
# Print the type of fk_module
print(type(fk_module))
print(fk_module)
Since the point has been added in the PythonPath environment variable, the Python program can always load the module under the same path. So, the above program can successfully import the FK_Module module.
Run the above program, you can see the following output results:
<class ‘module’>
<module ‘fk_module’ from ‘C:\Users\mengma\Desktop\fk_module.py’>
From the output result, when the program is imported into fk_module, the output statement in the module is automatically executed when IMPORT. This program also contains a variable that is the same as the module, the type of variable is Module.
The essence of the import module using the "import fk_module" is to load all the code in fk_module.py to memory and execute, and then assign the entire module content to variables with the same name as the module, the variable is Module, and in this module All programs defined are equivalent to members of the module object.
Let's try againfrom...import The statement is executed, for example, using the following procedure to test the module:
from fk_module import name, hello
print("================")
print(name)
print(hello)
# Print fk_module
print(fk_module)
Run the above program, you can see the following output results:
fkit
<function hello at 0x0000000001E7BAE8>
Traceback (most recent call last):
File “fk_module_test2.py”, line 22, in
print(fk_module)
NameError: name ‘fk_module’ is not defined
As can be seen from the output results, even if usedfrom...import Only the components in the module are imported. The output statements in the module will be automatically executed when IMPORT, which means that Python will still load and execute the code in the module.
The essence of members in the import module in the "from fk_module import name," from fk_module import name, the nature of the FK_MODULE.PY is loaded into memory and execute, and then import only the specified variables, functions, etc., and will not import the entire module, so The above program will see an error prompt when the FK_MODULE is output:name 'fk module' is not defined。
After importing the module, you can see a name in the directory where the module file is located.pycache"The folder, open the folder, you can see that Python generates a * .cpython-36.pyc file for each module, such as python generates a fk_ module.cpython-36.pyc file for the FK_Module module, the file is actually It is Python to compile the generated bytecode for the module to enhance the operational efficiency of the module.
First look at an example, modify the program file at the beginning of this section as follows:
import fk_module
import fk_module
print("================")
# Print the type of fk_module
print(type(fk_module))
print(fk_module)
The result of the operation is:
<class ‘module’>
<module ‘fk_module’ from ‘C:\Users\mengma\Desktop\fk_module.py’>
It can be seen that the fk_module module is imported into the modified program, which is completely unnecessary, which is imported twice here is just a point: Python is very intelligent. Although the FK_MODULE module is imported twice, but finally run the program, we see that the output statement only outputs a "this is fk_module", which means that the second imported fk_module module does not work, this is Python's "intelligence" The place.
When the program is repeatedly imported into the same module, Python will only import once. The truth is simple, because these variables, functions, classes and other program units only need to define once, why bother to import multiple times? Conversely, if Python allows multiple times to be introduced, it may lead to serious consequences. For example, the program defines two modules of Foo and BAR. If the FOO module imports the BAR module, the BAR module imports the FOO module, which seems to form an infinite loop import, but because Python will only import it once, this unlimited loop is imported. The problem can be avoided.
In fact, when we import a module to the file, the imported variables, functions and classes that are not previously described in this module (single underline "_" or double underscore "__"). Therefore, if we don't want a member in the module file to be used in other files, you can add an underscore before its name.
The demo.py module file and Test.py file created in the previous section as an example (they are located in the same directory), and the contents of each include:
#demo.py
def say():
Print ("Life is short, I learn Python!")
def CLanguage():
Print ("C language : http://c.biancheng.net")
def disPython():
Print ("Python Tutorial: http://c.biancheng.net/python")
#test.py
from demo import *
say()
CLanguage()
disPython()
Execute the Test.py file, the output is:
Life is short, I learn Python!
C language : http://c.biancheng.net
Python tutorial: http://c.biancheng.net/python
On this basis, if the DISPYTHON () function in the demo.py module does not want other files to be introduced, simply change its name to _dispython () or __dispython (). After modification, execute Test.py again, the output result is:
Life is short, I learn Python!
C language : http://c.biancheng.net
Traceback (most recent call last):
File “C:/Users/mengma/Desktop/2.py”, line 4, in
disPython()
NameError: name ‘disPython’ is not defined
Obviously, the Test.py file cannot be used in the Test.py file.
In addition to this, you can also provide with the moduleall Variables, the value of this variable is a list, stores some of the names of some members (variables, functions or classes) in the current module. Set it in the module fileall Variables When other files are imported into the module in the form of "from module name import *", it can only be used.all The member specified in the list.
That is, only the module imported in the "FROM module name import *", when the module is providedall When variables, only members specified by the variable can be imported, and the unidentified member cannot be imported.
For example, modify the code in the Demo.py module file:
def say():
Print ("Life is short, I learn Python!")
def CLanguage():
Print ("C language : http://c.biancheng.net")
def disPython():
Print ("Python Tutorial: http://c.biancheng.net/python")
__all__ = ["say","CLanguage"]
visible,all Variables contain only SAY () and Clanguage () function names, and does not contain the name of the DISPYTHON () function. The test.py file directly directly, and its execution results are:
Life is short, I learn Python!
C language : http://c.biancheng.net
Traceback (most recent call last):
File “C:/Users/mengma/Desktop/2.py”, line 4, in
disPython()
NameError: name ‘disPython’ is not defined
Obviously, for Test.py files, the DISPYTHON () function in the demo.py module is not introduced so that call is illegal.
Declare again,allVariables are limited to the "FROM Module Name Import *" in other files. That is, if the module is introduced using the following two ways, thenall The setting of the variable is invalid.
Take the demo.py module file and the test.py file as an example, modify their code as follows:
#demo.py
def say():
Print ("Life is short, I learn Python!")
def CLanguage():
Print ("C language : http://c.biancheng.net")
def disPython():
Print ("Python Tutorial: http://c.biancheng.net/python")
__all__ = ["say"]
#test.py
import demo
demo.say()
demo.CLanguage()
demo.disPython()
Run the test.py file, its output is:
Life is short, I learn Python!
C language : http://c.biancheng.net
Python tutorial: http://c.biancheng.net/python
It can be seen, although it is set in the demo.py module file.all Variables, but when it is introduced by "Import Demo",all Variables will not work.
Take Demo.py and Test.py as an example, modify the code in the Test.py file, as shown below:
from demo import say
from demo import CLanguage
from demo import disPython
say()
CLanguage()
disPython()
Run Test.py, the output result is:
Life is short, I learn Python!
C language : http://c.biancheng.net
Python tutorial: http://c.biancheng.net/python
In actual development, a large project often needs to use hundreds of thousands ofPython Module, if they are put together, they are not well managed. Moreover, using the module can effectively avoid the conflict of variable names or function names, but what if the module name is repeated? Therefore, Python proposed the concept of package.
What is the package? Simple understanding, the package is the folder, but there must be a name "in the folder"init.py "file.
Note that this is the provisions of Python 2.x, and in Python 3.x,init.py is not necessary to make it.
One must be established in the directory of each packageinit.py module, can be an empty module that writes some initialization code, which is to tell Python to process the directory as a package.
Notice,init.py is different from other module files, the module name of this module is notinitBut it is the name. For example, in the settings packageinit.py file, its module name is Settings.
The package is a folder containing multiple modules, which is still a module, so the package can also be included. For example, in the previous chapter, we can find the name-up folder in the lib \ site-packages installation directory after installation of the Numpy module. It is the installed Numpy module (actually a package), what it contains Figure 1 shows.

Figure 1 Numpy package (module)
As can be seen from Figure 1, in the NUMPY package (module), there must be includedinit.py file, there are module source files such as Matlib.py and Core (also modules). This is confirming that we have just said, the essence of the package is still a module, and the package can contain a package.
Python Library: Compared to modules and packages, libraries are a bigger concept, for example, there are a lot of packages in each library in the Python standard library, and there are several modules in each package.
《Python package"The section has been mentioned that the package is actually a folder, more precisely, is an included"init.py "file folder. So, if we want to manually create a package, just do the following 2 steps:
For example, now we create a very simple package, the name of the package is MY_PACKAGE, which can be followed by 2 steps above:
Create a folder, its name is set to my_package;
Add one in this folderinit.py file, this file can not be written in any code. However, the following code is written here:
'''
http://c.biancheng.net/
Create the first Python package
'''
print('http://c.biancheng.net/python/')
can be seen,initIn the .py file, 2 part information is included, which is the description information of this package and a print output statement.
Thus, we successfully created a Python package.
After you create a bag, we can add a module to the package (you can also add packages). Here, add 2 modules to my_package packets, named Module1.py, Module2.py, each containing code, respectively (readers can copy directly):
# module1.py module file
def display(arc):
print(arc)
# Module2.py module file
class CLanguage:
def display(self):
print("http://c.biancheng.net/python/")
Now, we create a package with the following file structure:
my_package
┠── init.py
┠── module1.py
┗━━ module2.py
Of course, there are other packages in the package, but here no longer demonstrate, interested readers can adjust the structure of the package.
Through the previous learning we know that the package is actually inherently a module, so the syntax of the import module also applies to the import package. Regardless of our custom package, or import the third party package downloaded from him, the import method can be attributed to the following three types:
Import package [. Module name [AS alias]]]From package name IMPORT module name [AS alias]From package. Module name Import member name [AS alias]The part of [] is included, it is an optional portion, that is, it can be used, or it can be directly ignored.
Note that while importing packages will be generated in the package directoryinit.cpython-36.pyc filepycache folder.
Take the MY_PACKAGE package in front as an example to import the Module1 module and use the members in the module to use the following code:
import my_package.module1
my_package.module1.display("http://c.biancheng.net/java/")
The result of the operation is:
http://c.biancheng.net/java/
It can be seen that after the specified module in the package is imported by this grammatical format, the "package name. Module name" is needed to use the member (variable, function, class) in this module. Of course, if you use the AS to the package. Module name ", use this alias to use this alias as the method in this module, for example:
import my_package.module1 as module
module.display("http://c.biancheng.net/python/")
The result of the program is:
http://c.biancheng.net/python/
In addition, when importing the specified package directly, the program automatically performs the corresponding folder of the package.initThe code in the .py file. E.g:
import my_package
my_package.module1.display("http://c.biancheng.net/linux_tutorial/")
Import the package directly, do not import all the modules in the package into the program, its role is only imported and executed under the packageinit.py file, therefore, run the program, executinginitThe code in the .py file, also throws AttributeError exception (the object of access does not exist):
http://c.biancheng.net/python/
Traceback (most recent call last):
File “C:\Users\mengma\Desktop\demo.py”, line 2, in
my_package.module1.display(“http://c.biancheng.net/linux_tutorial/”)
AttributeError: module ‘my_package’ has no attribute ‘module1’
We know that the essence of the package is the module. When the module is imported, the current program will contain a variable with the module name and type MODULE, the import package is also true:
import my_package
print(my_package)
print(my_package.__doc__)
print(type(my_package))
The result of the operation is:
http://c.biancheng.net/python/
<module ‘my_package’ from ‘C:\Users\mengma\Desktop\my_package\init.py’>
http://c.biancheng.net/
Create the first Python package
<class ‘module’>
Take the Module1 module in the introduction MY_PACKAGE package as an example, the implementation code of this syntax format is as follows:
from my_package import module1
module1.display("http://c.biancheng.net/golang/")
The result of the operation is:
http://c.biancheng.net/python/
http://c.biancheng.net/golang/
It can be seen that after using this syntax format Import package, you do not need to bring a package prefix when using its member, but you need to have a module name prefix.
Of course, we can also define an alias for the specified module imported by AS, for example:
from my_package import module1 as module
module.display("http://c.biancheng.net/golang/")
The output result of this program is identical to the above program.
Similarly, since the package is also a module, then this grammar format is naturally supported.From IMPORT * This kind of writing, is the same as the IMPORT package, just put the packageinit.py file import and execute.
This syntax format is used to import the "Pack. Module" in the program (variables, functions, or classes). By importing variables (functions, classes) imported, you can use the variable name (function name, class name), for example::
from my_package.module1 import display
display("http://c.biancheng.net/shell/")
The result of the operation is:
http://c.biancheng.net/python/
http://c.biancheng.net/shell/
Of course, you can also use AS to import a member, for example:
from my_package.module1 import display as dis
dis("http://c.biancheng.net/shell/")
The result of the program is the same as above.
In addition, when using this syntax format to load the specified module of the specified package, you can use * instead of the member name, indicating that all members loaded under the module. E.g:
from my_package.module1 import *
display("http://c.biancheng.net/python")
In the previous chapter, the creation and import of the package has been explained in detail, and a large number of instances provide, although it can work normally, there is a common problem, that is, members of the package (variables, functions or classes) of the package module (variables, functions or classes) The code contains many Import import statements, very cumbersome.
To solve this problem, you need to understand the packageinitThe effect and usage of the .py file.
We know that the import package is equivalent to importing the package.init.py file, therefore it isinitThe .py file directly writes the variables, functions, and classes of the module functionality, but actually and recommend that you do this because the main role of the package is to include multiple modules. therefore initThe main role of .py file is to import other modules within the package.
In other words, byinit.py file Use the import statement to import the necessary modules, so when you import this package to other programs, you can directly import the package name, which is used.IMPORT package name(orFrom IMPORT *The form is in the form.
In the previous section, we have created a good my_package package that contains the Module1 module, the module2 module, andinit.py file. Now to my_package packageinitThe .py file is written as follows:
# Import Module1 module from the current package
from . import module1
#from .module1 import *
# Introduced from the current package into the module2 module
#from . import module2
from .module2 import *
It can be seen,initThe .py file is used in points (.) to indicate the package name of the current packet, in addition to this, the usage of the FROM IMPORT statement is identical to the usage of the package in the program.
Usage of from ... import statement, readablePython creates a package, import package"Detailed understanding.
In general,initThe .py file is imported into the module in the following two ways:
# From the current package Guide the specified module
import. import module name
# From. Module name Import all members into the package
Modular name import *
The first method is used to import the specified module in the current packet (module) so that the module can be used in the package. When other programs use members within the module, you need to add a "package name. Module name" as a prefix, for example:
import my_package
my_package.module1.display("http://c.biancheng.net/python/")
The result of the operation is:
http://c.biancheng.net/python/
In the second method, when importing all members from the specified module, use this import mode, when using the member of the module in other programs, as long as the package name is used as a prefix. For example, as follows:
import my_package
clangs = my_package.CLanguage()
clangs.display()
The result of the operation is:
http://c.biancheng.net/python/
In the previous chapter, the creation and use of modules and packages (strictly, the package is also a module), some readers may have such a question, that is, after the module or package, how do you know which module contains which Members (variables, functions or classes)?
This section introduces two methods to you in this section.
In fact, in the study of the previous chapter, DIR () functions have been used multiple times. With the DIR () function, we can view all members (including variables, functions, and classes) included in a specified module. Note that all members referied herein not only contains members of the module available to us, but also all names that start and end with double underscore "__", and those "special" named members are used in this module. And do not want to be called by other files.
Here is an imported String module as an example, the String module contains a large number of methods related to the operation string, and below through the DIR () function is included in the module:
import string
print(dir(string))
The result of the program is:
[‘Formatter’, ‘Template’, ‘_ChainMap’, ‘_TemplateMetaclass’, ‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_re’, ‘_string’, ‘ascii_letters’, ‘ascii_lowercase’, ‘ascii_uppercase’, ‘capwords’, ‘digits’, ‘hexdigits’, ‘octdigits’, ‘printable’, ‘punctuation’, ‘whitespace’]
It can be seen that the module member acquired by the DIR () function includes not only a member of the use of external files, but also contains many "special" (names with 2 underscores and ends), listing these members, for us There is no practical meaning.
Therefore, it is recommended to recommend a method of ignoring a special member of the display DIR () function output. Still use String module as an example:
import string
print([e for e in dir(string) if not e.startswith('_')])
The result of the program is:
[‘Formatter’, ‘Template’, ‘ascii_letters’, ‘ascii_lowercase’, ‘ascii_uppercase’, ‘capwords’, ‘digits’, ‘hexdigits’, ‘octdigits’, ‘printable’, ‘punctuation’, ‘whitespace’]
Obviously, by the list of derivation, the members useful to us and displayed on the basis of the DIR () function output result.
In addition to using the DIR () function, you can useall Variables can also view all members contained in the module (package) with this variable.
Still taking the String module as an example, an example:
import string
print(string.__all__)
The result of the program is:
[‘ascii_letters’, ‘ascii_lowercase’, ‘ascii_uppercase’, ‘capwords’, ‘digits’, ‘hexdigits’, ‘octdigits’, ‘printable’, ‘punctuation’, ‘whitespace’, ‘Formatter’, ‘Template’]
Obviously, compared with the DIR () function,all When the variable is viewed by the specified module member, it does not display special members in the module, and will be sorted according to the name of the member.
However, it should be noted that not all modules are supportedall Variables, so only the DIR () function can only be used for members who get some modules.
Use the DIR () function andall On the basis of variables, although we can know all available members (variables, functions, and classes) in the specified module (or package), such as:
import stringprint(string.__all__)
The result of the program is:
[‘ascii_letters’, ‘ascii_lowercase’, ‘ascii_uppercase’, ‘capwords’, ‘digits’, ‘hexdigits’, ‘octdigits’, ‘printable’, ‘punctuation’, ‘whitespace’, ‘Formatter’, ‘Template’]
But for the above output results, for users who are not familiar with the String module, it is still unclear what these names are indicated by them, and it is more unclear what features are available.
In response to this situation, we can use the help () function to get the help information of the specified member (even the module). Take the MY_PACKAGE package created in front of the previous section as an example, which containsinit.py, module1.py and module2.py These 3 modules, their respective contents are as follows:
# *** __ init__.PY content ***
from my_package.module1 import *
from my_package.module2 import *
# *** Module1.py in content ***
# module1.py module file
def display(arc):
'''
Direct output specified parameters
'''
print(arc)
# *** Module2.py in ***
# Module2.py module file
class CLanguage:
'''
Clanguage is a class that contains:
DISPLAY () method
'''
def display(self):
print("http://c.biancheng.net/python/")
Now let's take a DIR () function, see how much available in my_package packages:
import my_package
print([e for e in dir(my_package) if not e.startswith('_')])
The result of the program output is:
[‘CLanguage’, ‘display’, ‘module1’, ‘module2’]
Through this output, you can learn that in the MY_PACKAGE package, there are more than 4 members for us to use. Next, we use the help () function to see the specific meaning of these members (as an example of Module1):
import my_package
help(my_package.module1)
The output result is:
Help on module my_package.module1 in my_package:
NAME
MY_PACKAGE.MODULE1 - # Module1.py module file
FUNCTIONS
display(arc)
Direct output specified parameters
FILE
c:\users\mengma\desktop\my_package\module1.py
By output results, it is understood that module1 is actually a module file that contains a display () function, the function of which is the direct output specified ARC parameter. At the same time, the specific storage location of the module is also shown.
Of course, interested readers can also try to run as follows:
# Output specific information of Module2 members
help(my_package.module2)
# Output DISPLAY member specific information
help(my_package.module1.display)
# Output specific information of the Clanguage member
help(my_package.module2.CLanguage)
It is worth mentioning that the reason why we can use the help () function to view the specific members of the specific member, because the member itself contains a document that represents its own identity (essence is a string, where the site is located inside the member). As mentioned earlier, whether it is a function or class, you can usedoc Attributes get their documentation, modules are no exception.
Take the display () function in the MY_PACKAGE package module, we try to usedoc Variables Gets its description documentation:
import my_package
print(my_package.module1.display.__doc__)
The result of the program is:
Direct output specified parameters
In fact, the bottom layer of the help () function is also withdoc Attributes are implemented.
So, if you use a Help () function ordoc Attributes, still unable to meet our needs, you can also use the following two methods:
As mentioned above, when the specified module (or package) does not explain the document, only the Help () function ordoc Attributes cannot help us understand the specific function of the module (package). In this case, we can passfile Properties Find the specific storage location of the module (or package) file, directly view its source code.
Take the MY_PACKAGE package created in front of the previous section as an example, the following code tries to usefile Property Gets the storage path of the package:
import my_package
print(my_package.__file__)
The result of the program output is:
C:\Users\mengma\Desktop\my_package_init_.py
Note that because when introducing a My_Package package, it is actually performed.init.py file, so see the storage path of the MY_PACKAGE package, outputinitThe storage path of the .py file.
Take the String module as an example:
import string
print(string.__file__)
The result of the program output is:
D:\python3.6\lib\string.py
From this, by callingfile The absolute path of the attribute output, we can easily find the source file of the module (or package).
Note, not all modules are availablefile Attribute, because it is not all the implementation of all modulesPython Language, some modules use other programming languages (such as C language).
When performing a Python program development, in addition to using the Python built-in standard module and our custom modules, there are many third-party modules that can be used, and these third-party modules can use the Python's official view page (https: // pypi) .org /) found.
Before using a third-party module, you need to download and install the module before you can import and use it as used as a standard module and custom modules. Therefore, this section mainly explains how to download and install a third party module.
Download and install third-party modules, you can implement the PIP command provided by Python. The syntax format of the PIP command is as follows:
PIP Install | Uninstall | List Module Name
Among them, install, uninstall, and list are commonly used command parameters, respective meaning:
Take the Numpy module as an example (this module is used for scientific calculations), you can enter the following code in the Command Line window:
pip install numpy
Execute this code, it will automatically install the NUMPY module online. After the installation is complete, the results shown in Figure 1 are displayed:

Figure 1 Numpy module installation success schematic
The PIP command will download the third-party module that completes the download, and the default is installed in the \ lib \ site-packages directory in the Python installation directory. Open this directory, you will find the Numpy package, which is the Numpy folder, as shown in Figure 2.

Figure 2 Numpy package content diagram
As mentioned earlier, for the introduction module in the program, the \ lib \ site-packages directory is a directory that Python will definitely search, so the module in this directory can be introduced directly, for example:
# directly into the Numpy module
import numpy as nu
# Use the development function in the NUMPY module
print(nu.sqrt(16))
The result of the operation is:
4.0
With the PIP command, we can download and install a lot of third-party modules. If you want to see which modules (including standard modules and third-party modules) in Python, you can enter the following command in idle:
help(‘modules’)
On this basis, if you just want to see a third-party module that has been installed, you can use the following command:
pip list
Tip: In large programs, many modules are often important. It is recommended that beginners prefer the standard modules provided by Python when importing modules, and then import a third-party module and finally import custom modules.
Python basics - Package - Module learning notes 1. The module is a Python file What is included in the module function class Test code Import module 2. Module search path and storage View instance Mod...
Package and module management Module Command import from importlib.reload (module) as Package __init__ initialization packet introduced why Code reuse Namespaces Or services for data sharing Step 1. L...
Similar to a single module, a module package corresponds to a directory (and a module corresponds to a .py file). andPackage import is to treat a directory on the computer as a namespace, and the modu...
Python provides a set of technologies that can be easily shared, including modules and some development tools: Modules allow you to organize code reasonably to achieve optimal sharing. The release too...
Argparse module use tutorial 1, ArgParse introduction 2, unused ArgParse example 3, use the ArgParse example 2.1 ARGPARSE simple example 2.2 ArgParse Advanced Example 2.2.1 Optional Parameter Settings...
First of all, the PY file we know in Python is a module, that is, the Python source code file at the end of PY is a module. 1. Module use The module needs to be imported before using the tool in the m...
Recently, I need to provide a python code containing multiple neural network inferences for gRPC to call, that is, I need to encapsulate a server that supports gRPC on the basis of this main program. ...
A: import Import module will execute the code in the source file is first imported If the module has been loaded into memory, a result of introducing the direct memory references introduced eval: perf...
[Python learning note 6] Python module, package and program Module import and import statement Document organization and package Standard library and package management tools Module import and import ...
#You cannot always use import first2 to import modules, because there are many modules and you need to classify them #Secondly, you may define modules with the same name in different categories #So he...