Excerpt from the python study manual for the record.
The client can execute the import or from statement. If the module is not loaded, these statements will search, compile, and execute the module file program. The main difference is that import reads the entire module, so it must be defined before its variable name can be read; from will get (or copy) module-specific variable names.
import makes a variable name refer to the entire module object, so the module's properties must be obtained by the module name (e.g., module1.printer). and from will copy the variable name to another scope, so it can use the copied variable name directly in the script without going through a module (e.g., printer).
from statement has the potential to break namespaces. If you import variables using from, and those variables happen to be duplicated with existing variables in scope, the variables will be quietly overwritten. This is not a problem when using import statements, because its contents must be obtained by the module name. However, when using from, this is not a big problem in practice, as long as you understand and anticipate this to happen, especially if you clearly list the import variable names (e.g., from module import x, y, z).
On the other hand, when used with the reload call, the from statement has a serious problem, because the imported variable name may refer to a previous version of the object. Furthermore, the form from module import * can indeed break the namespace and make variable names difficult to understand, especially when importing more than one file.
A more pragmatic suggestion is that simple modules generally tend to use import rather than from. Most from statements are used to explicitly enumerate the desired variables, and are limited to using the form from * only once per file. This way, any undefined variable name can be considered to exist in the module referenced from *. You really have to use import when you have to use the same variable name variable defined in two different modules, in which case you can't use from.
I talked a lot, I don't know what to say, let's talk about it briefly.
- import Module # Introduce modules
- from Module import Other # Introduce classes, functions, or variables in the module
- from Module import * # Introduce all 'public' members in the module
In layman's terms:
import a class #把整个一班的学生引入了进来
from a group of import Xiao Wang #只把一般的小王引入了进来
For example:
The time package is an example, and the following two writing methods are the same, as follows:
|