首先我们自定义一个模块,
我们把他命名为test_modular
这个模块里面,有一个测试函数test_function
源代码如下:
#模块名称为:test_modular.py #
def test_function(a,b): #函数名称为test_function(a,b),函数使用时候要提供两个参数
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a, b)
#这里首先定义了一个模块,名字为test_modular,存在相同路径,保存为test_modular.py
#为以后调用准备模块名称为test_modular 函数名称为 def test_function
#在定义模块时候,模块名称和函数名称都是可以随便起名的,任意的符合规则的。
好了,我们的模块准备好了。下面我们在另外一段代码中调用这个函数
import test_modular # 调入我们已经存在的模块
test_modular.test_function(36,12) #调入我们的自定义的模块和函数,并给入数据36和12
运行结果是:
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
runfile(‘D:/python/pythonProject/test.py’, wdir=‘D:/python/pythonProject’)
48
24
432
3.0
36 12
OK,这就是最简单的自定义模块、函数及调用方式。
另外还可以给调用模块重新命名,方式如下:
import test_modular as p # 这里是调入test_modular模块,并给他命名为p
p.test_function(36,12)
OK,给调用模块重新命名,方式就这么简单。
我们还可以给调用模块里面的函数重新命名,方式如下:
# 这里把test_modular.test_function()函数改名为 s 后调用#
from test_modular import test_function as s
s(36,12)
所有运行结果一直。
这就是自定模块的使用方法。