Two import methods for the Python module. We need to keep learning when using it. In fact, as long as we have mastered the writing of relevant code in actual applications, You should know when to use this method.
One way is to import module, which you have read in section 2.4 "Everything is object. Another method is to accomplish the same thing, but it has a subtle but important difference with the first one.
The basic syntax of from module import is as follows:
- from UserDict import UserDict
It is very similar to the import module syntax you are familiar with, but there is an important difference: UserDict is directly imported to a local namespace, so it can be used directly, you do not need to specify the module name. You can import independent items or use from module import * to import everything.
The from module import * in Python is like the use module in Perl; the import module in Python is like the require module in Perl.
The from module import * in Python is like the import module * in Java; the import module in Python is like the import module in Java.
- import module vs. from module import
- >>> import types>>> types.FunctionType <type 'function'
>>>> FunctionType Traceback (innermost last): File "
<interactive input>", line 1, in ?NameError: There is no
variable named 'FunctionType'>>> from types import
FunctionType >>> FunctionType <type 'function'>
The types module does not contain methods, but represents attributes of each Python object type. Note that this attribute must be limited by the module name types. FunctionType itself is not defined in the current namespace; it only exists in the context of types. This syntax imports the FunctionType attribute from the types module to a local namespace. Currently, FunctionType can be directly used and is irrelevant to types.
- Remote rejection of malformed query in Apache mod_python Module
- How to Use the Python module to parse the configuration file?
- Zipfile In the Python Module
- Research on the Python Module
- Introduction to the Python Module
When should you use the from module import?
If you want to access the attributes and methods of a module frequently and do not want to enter the module name over and over again, use from module import. If you want to selectively import some attributes and methods, instead of others, use from module import. If the attributes and methods in a module have the same name as one of your modules, you must use the import module to avoid name conflicts. In addition to these situations, the rest is just a style issue. You will see the Python code written in two ways.
Try to use less from module import * because it is difficult to determine where a special function or attribute comes from, and it will make debugging and refactoring more difficult.