用举例的形式说明两种方式的异同点
首先创建两个文件,分别为a.py和b.py
a.py内容如下:
#a.py
def test():
print('this is a.test')
print('this is a.py')
b.py内容如下:
#b.py
from a import test
def test():
print('this is b.test')
print('this is b.py')
test()
运行b.py结果显示:
变种一、
把b.py内容改成如下:
#b.py
import a
或者
#b.py
from a import test
运行b.py结果显示:
this is a.py
变种一 解释说明:
import 和from import都会运行a.py中可执行的语句,即print 'this is a.py'
变种二、
1、把b.py内容改成如下:
#b.py
from a import test
def test():
print('this is b.test')
print('this is b.py')
test()
运行b.py结果显示:
2、把b.py内容改成如下:
#b.py
from a import test
#def test():
# print('this is b.test')
print('this is b.py')
test()
运行b.py结果显示:
变种二 解释说明:
用from import 时,如果b.py和a.py有同名的函数,b.py中的函数生效,a.py中的函数不生效
变种三、
1、把b.py内容改成如下:
#b.py
import a
def test():
print('this is b.test')
prin('this is b.py')
test()
运行b.py结果显示:
2、把b.py内容改成如下:
#b.py
import a
def test():
print('this is b.test')
print('this is b.py')
a.test()
运行b.py结果显示:
变种三 解释说明:
用import时,要引用a.py中的函数,格式为a.函数名,即本例中的a.test()
变种四、
1、把b.py内容改成如下:
#b.py
from a import test
def test():
print('this is b.test')
print('this is b.py')
a.test()
运行b.py结果显示错误:
NameError: name ‘a’ is not defined
变种四 解释说明:
用from import时,要引用a.py中的函数,不能用a.函数名这种形式

本文通过四个变种实例,详细解释了Python中`import`和`from...import`两种导入方式的差异。从运行效果和作用域两方面进行阐述,包括对同名函数的处理以及如何正确引用模块内的函数。

被折叠的 条评论
为什么被折叠?



