This article mainly introduces the differences between the two import methods of the python module. If you are not familiar with the methods of the two import modules of the python module, you may have used the following articles to learn more about it. I hope you will learn more about it. The following is a detailed description of the article.
Python has two methods for importing modules. They are both useful. You should know when to use them. 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. Example:
5.2. 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.
- Detailed description of relative paths and absolute paths for getting started with Python
- How to Use python pylint to check related items
- Sample Code for the python Random Number Module
- Detailed introduction to the python list learning and sorting list and array
- How to render the sequence details of tuples in Python Django
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.