Difference between from import and import in Python?

In any case, when referring to imported things later, you have to start from the place marked by import, until the last function, for example:

The following three are all correct ways of writing, calling the join function of the path sub-item in the os package, which is used to add the paths to a complete path:

from os.path import join
print(join('C:\\windows', 'system32'))
Note: The join function is introduced from the path (package) of os (module), and the subsequent use can be directly used with join(), but writing path.join() and os.path.join() will cause errors.

import os
print(os.path.join('C:\\windows', 'system32'))
Note: When the module of os is introduced, the subsequent use needs to be written in full and used os.path.join(), but writing path.join() and join() will cause errors, and the error message indicates that it is undefined ('xxx' is not defined)

import os.path
print(os.path.join('C:\\windows', 'system32'))
Note: The path (package) in os (module) is introduced, and the subsequent use also needs to be written in full. After writing the content after import, continue to reference, use os.path.join(), write path.join() and join() will make an error, and the error description will be reported. Same as above.

Summarize:

Use import to import a module. When using a method in the module, the restriction name should be added in front, that is, the package in that module and the method in the package.

When using from ... import ... to import a method of a module, when using a method of a package in the module, it can be used directly without adding a restriction name.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383594&siteId=291194637