import和from...import

import和from...import

Use jimport general form ... import and import module

Below spam.py 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
    

A, import the module name

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



Time introduced by the above module () column:

Three things happen import

  1. Generation time in memory, called namespace.
  2. Run time.py file, then the name of the file space in the time.py into the name space of time.
  3. The name of the time and space to point import from ... impot.py (current file import time module) namespace
  4. Use import time import method can only be used when the time. Method name (), can not be directly method name.

Repeat the import module to create good results before drinking directly, the document will not repeat the module, that is repeated import will happen: spam = spam = module name space memory address.

A plurality of modules may be introduced at the same time

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

Two, form the module name import specific functions

from time import gmtime

from ... import ... first import module happened three things:

  1. Create a module to module, whichever namespace
  2. Execution module corresponding file, will perform the namespace name generated in the process are thrown into the module
  3. Get a name in the current namespace executable file, the name of the module directly to a particular name, which means you can not add any prefix directly
  • Pros: do not add a prefix code more streamlined
  • Disadvantages: easily conflict with the currently executing file namespace name

Import all functions within the file:

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

Three, import and from ... import of similarities and differences

  1. Same point
    1. Both modules will execute the corresponding file, the name space will have two modules.
    2. When the two function calls, we need to go looking for the definition of the scope of a relationship, regardless of the location of the call.
  2. difference
    1. import need to add a prefix, form ... import ... no need to add the prefix

Guess you like

Origin www.cnblogs.com/chenziqing/p/11359923.html