python中import和from import的区别

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用举例的形式说明两种方式的异同点

首先创建两个文件,分别为a.pyb.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结果显示:

this is a.py
this is b.py
this is b.test

变种一、

把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结果显示:

this is a.py
this is b.py
this is b.test

2、把b.py内容改成如下:

#b.py
from a import test
#def test():
#    print('this is b.test')
print('this is b.py')
test()

运行b.py结果显示:

this is a.py
this is b.py
this is a.test

变种二 解释说明:
用from import 时,如果b.pya.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结果显示:

this is a.py
this is b.py
this is b.test

2、把b.py内容改成如下:

#b.py
import a
def test():
    print('this is b.test')
print('this is b.py')
a.test()

运行b.py结果显示:

this is a.py
this is b.py
this is a.test

变种三 解释说明:
用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.函数名这种形式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值