想在a.py里面定义2个函数test1和test2
a.py
def test1(str):
print('test1:',str)
def test2(str):
print('test2:', str)
b.py
import a
a.test1(33)
a.test2(44)
正常引用import a,调用里面的函数,需要把包名也打全
执行结果:
test1: 33
test2: 44
c.py
from a import test1
test1(5)
# a.test2(6) # 报错:NameError: name 'a' is not defined,因为没有导入a的test2
# test2(6) # 报错 NameError: name 'test2' is not defined
这里值导入了a里面的test1,使用的时候不需要加上a. 前缀
因为没有导入test2,所以输入a.test2会报错 ,单独使用test2也报错
执行结果:
test1: 5
d.py
from a import *
test1(7)
test2(8)
import *意思是导入a 里的所有包,可以直接不加a.前缀直接使用a里的方法,可以少打一个包名,但是容易造成命名空间混淆
执行结果:
test1: 7
test2: 8
e.py
from a import *
def test1(str):
print('d.py里的test1',str)
test1(7)
test2(8)
test1(9)
这里的test1调用的是e.py里的test1
执行结果:
d.py里的test1 7
test2: 8
d.py里的test1 9