Home > Backend Development > Python Tutorial > Import usage in python (code example)

Import usage in python (code example)

藏色散人
Release: 2019-03-30 15:06:10
Original
5544 people have browsed it


#When writing code, you may need certain modules. So we import these modules using a single line of code in Python.

But what if we only know the name of the required module at runtime? How do we import that module? We can use Python's built-in __import__() function. It also helps to import modules at runtime.

Syntax:

__import__(name, globals, locals, fromlist, level)
Copy after login

Parameters:

##name: The name of the module to be imported

globals and locals: Interpretation names (global variables and local variables)

formlist: Object or child to be imported Modules (as a list)

level: Specifies whether to use absolute or relative imports. The default value is -1 (absolute and relative).

Example 1:

# 导入numpy
np = __import__('numpy', globals(), locals(), [], 0) 
  
# array from numpy 
a = np.array([1, 2, 3]) 
  
# prints the type 
print(type(a))
Copy after login

Output:


<class &#39;numpy.ndarray&#39;>
Copy after login

Example 2:

The following two sentences have the same meaning and have the same effect.

np = __import__(&#39;numpy&#39;, globals(), locals(), [&#39;complex&#39;, &#39;array&#39;], 0) 
  
comp = np.complex
arr = np.array
Copy after login

__import__() is not necessary in daily Python programming. Its direct use is rare. But sometimes, this feature comes in handy when you need to import a module at runtime.

Related recommendations: "

Python Tutorial"

This article is an introduction to the usage of import in python. I hope it will be helpful to friends in need!


The above is the detailed content of Import usage in python (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template