When writing python, the following description written as import almost always appears.
import sys
I used to copy and paste it as a magic, but gradually I couldn't avoid it, so I checked it properly.
--What is a module? --Basic import --import using from --How to import multiple objects (functions) -Import using * (wildcard) --Difference between module loading and object loading --Import by alias
In Python, a file in which functions and classes are written together is called a module. It's a .py file. It seems that a collection of multiple modules is called a library. There is a standard library in Python, which can be used by importing it.
It is ʻimport to load that module. If you do ʻimport <module name>
as shown below, the module will be imported as a module type object.
import math
You can see that math is imported as a module by printing with type
.
import math
print type(math)
>>>
<type 'module'>
>>>
It is also possible to directly import functions and classes in the module.
You can import with from <module name> import <function name>
.
The imported function can be executed by specifying the name.
Not only functions but also variables and classes may be imported, so they are referred to as
from math import pi
print(pi)
>>>
3.141592653589793
>>>
If you specify an object and import it, the math module is not imported.
from math import pi
print type(math)
>>>
NameError: name 'math' is not defined
>>>
It is also possible to import multiple objects at the same time.
from math import pi, radians
When loading the module, please note that the following description is recommended in PIP8.
# NG
import os, sys
# OK
import os
import sys
All objects can be imported using * (wildcard). However, it seems that it is not recommended because it is a slightly rough import method.
from math import *
The description at runtime differs between when only the module is loaded and when the object is loaded.
When only the module is loaded, it is necessary to specify <module name>. <Object name>
when executing the function.
import math
print(math.pi)#<Module name>.<Object name>
When an object is read, it can be executed by specifying only <object name>
.
from math import pi
print(pi)#<Object name only>
If only the module is loaded and only the object name is specified directly, an error will occur.
import math
print(pi)
It is also possible to call a module or object with any name.
import math as m
print(m.pi)
from math import pi as pai
print(pai)
https://note.nkmk.me/python-import-usage/
Recommended Posts