Import module in Python
Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.
import module_name
When import is used, it searches for the module initially in the local scope by calling __import__() function. The value returned by the function are then reflected in the output of the initial code.
3.141592653589793
import module_name.member_name
In the above code module math is imported, and its variables can be accessed by considering it to be a class and pi as its object.
The value of pi is returned by __import__().
pi as whole can be imported into our intial code, rather than importing the whole module.
Output:
3.141592653589793
from module_name import *
In the above code module math is not imported, rather just pi has been imported as a variable.
All the functions and constants can be imported using *.
Output:
3.141592653589793 720
As said above import uses __import__() to search for module, and if not found, it would raise ImportError
Output:
Traceback (most recent call last):
File "C:/Users/GFG/Tuples/xxx.py", line 1, in
import mathematics
ImportError: No module named 'mathematics'
0 comments:
Post a Comment