Tips: import & from

There are two ways to import or use the code from other package:

import mypkg

from mypkg import *

There is a big difference between them.
from 是变量名拷贝运算,而非变量名的别名机制

For example: there is a package called mypkg

# mypgk.py
X = 99
def printer():
  print (X)

如果我们在另一模块nested1.py内使用from导入两个变量名。

# nested1.py
from mypkg from X, printer   # copy names
X = 1      # change my 'X' only
printer()  # print mypkg's 'X' only which is still 99
% python nested1.py
99

BUT, 如果我们用import获得了整个模块,然后赋值某个点号运算的变量名,就会修改被导入模块中的变量的值。点号把python定向到了模块对象内的变量名,而不是导入者nested2.py的变量名。

# nested2.py 
import mypkg  # get module as a whole
mypkg.X = 1  # change mypkg's 'X'
mypkg.printer()

% python nested2.py
1

你可能感兴趣的:(Tips: import & from)