import和from...import

import和from...import

Generally use jimport and form...import to import modules

The following takes spam.py as the column

#spam.py
print('from the spam.py')
money = 1000
def read1():
    print('spam模块:',money)
def read2():
    print('spam模块')
    read1()
def change():
    global money
    money = 1
    

1. Import module name

# python看成一个手机,pip是应用管家,time就是应用管家里的一个应用,要用它,import
import time
time.time()



Use the above import module time() as a column:

3 things happen to import

  1. Generates a namespace called time in memory.
  2. Run the time.py file, then put the namespace in the time.py file into the time namespace.
  3. Point the namespace of time to the namespace of import and from...impot.py (the file that currently imports the time module)
  4. When using import time to import, the method can only be used time.method name(), not the method name directly.

The repeated import of the module will directly consume the previously created results, and will not repeat the execution of the module's file, that is, the repeated import will occur: spam=spam=The memory address of the module namespace.

Multiple modules can be imported at the same time

import time,os,requests
#建议使用下面
import time
import os
import requests

2. The specific function of the form module name import

from time import gmtime

from...import... 3 things happen when you first import a module:

  1. Create a module namespace based on the module
  2. Execute the file corresponding to the module, and throw the names generated during the execution process into the namespace of the module
  3. Get a name in the namespace of the current execution file, which directly points to a name in the module, which means that it can be used directly without adding any prefix.
  • Advantages: no need to add prefixes, the code is more streamlined
  • Disadvantage: prone to conflict with names in the namespace of the current execution file

Import all functions inside the file:

__all__ = ['money', 'read1']  # 只允许导入'money'和'read1'
form spam import *  # 导入模块内所有的功能,在函数调用的时候只能调用__all__内的函数和变量名,受到__all__的限制

3. The similarities and differences between import and from...import

  1. Same point
    1. Both will execute the file corresponding to the module, and both will result in the module's namespace.
    2. When both call functions, they need to go to the definition time to find the scope relationship, regardless of the location of the call.
  2. difference
    1. import needs to be prefixed, form...import... does not need to be prefixed