python中将函数存储在模块里(导入特定的函数)
1、将函数存储在模块里
def fun1(x): ## 在模块module1.py中定义三个函数
print(x.upper())
def fun2(x):
print(x.title())
def fun3(x):
print("---",x)
2、测试能否直接调用函数
>>> fun1("aaa")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
fun1("aaa")
NameError: name 'fun1' is not defined
>>> fun2("bbb")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
fun2("bbb")
NameError: name 'fun2' is not defined
>>> fun3("ccc")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
fun3("ccc")
NameError: name 'fun3' is not defined
3、从module1中导入特定的函数
>>> from module1 import fun1 ## 导入特定函数fun1, 导入方法from + 模块名 + import + 函数
>>> fun1("aaaa") ## 可以直接调用fun1
AAAA
>>> fun2("aaaa")
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
fun2("aaaa")
NameError: name 'fun2' is not defined
>>> fun3("aaaa")
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
fun3("aaaa")
NameError: name 'fun3' is not defined
>>> from module1 import fun2 ## 导入特定函数fun2
>>> fun2("aaaa")
Aaaa
>>> fun3("aaaa")
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
fun3("aaaa")
NameError: name 'fun3' is not defined
>>> from module1 import fun3 ## 导入特定函数fun3
>>> fun3("aaaa")
--- aaaa