用举例的形式说明两种方式的异同点
首先创建两个文件,分别为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.函数名
这种形式