use of import

First look at an example:

import math
 print (math.pi)# output 3.141592653589793

The above program uses the import statement, import math means to import the math.py module from the Python standard library, which is the method defined in Python to import modules

Multiple modules can be imported as follows: import math,time,sys

In addition to importing modules with import, there is another way to import modules, such as: from math import pi

Indicates that pi is imported from the math module into the current namespace. This statement will not import the entire math module. For example, there are sin and exp functions in the math module, which cannot be used in this statement, but can be used in the statement importing the entire math module. use

import math
print(math.pi)
print(math.sin(1))
print(math.exp(2))
#输出:
3.141592653589793
0.8414709848078965
7.38905609893065
from math import pi
print(pi)
print(sin(1))
print(exp(1))
#输出
3.141592653589793
Traceback (most recent call last):
  File "D:/practice/python program/practice2.py", line 7, in <module>
    print(sin(1))
NameError: name 'sin' is not defined

As can be seen from the above example, if you import the entire module, you will get all the objects in the entire module, and if you import a specified object, you can only get that object

What is the benefit of doing this, see the following example:

import math
print(math.pi) print(pi)
#输出
3.141592653589793
Traceback (most recent call last):
  File "D:/practice/python program/practice2.py", line 7, in <module>
    print(pi)
NameError: name 'pi' is not defined
from math import pi
 print (pi) 
#output
3.141592653589793

It can be found that if you access the pi object when importing the math module, you need to use math.pi. If you cannot access it directly using pi, an error will be reported. However, after using the from math import pi statement, you can directly access the pi object without adding the module name. access

It is also possible to separate multiple objects of the same module at a time with commas: from math import pi,sin,exp

You can also import all objects of the same module at one time: from math import *   However, it is not recommended to use this way, which is not conducive to the clarity of the code

You can also alias the module, such as: import math as m  

 

import math as m
print(m.pi)

 

It can be seen that the way to alias the module is: add an as statement at the end of the statement that exports the module, followed by the alias.

You can also alias the function, such as: from math import sin as s   We have aliased s for the sin function

 

Guess you like

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