我们可以将函数存储在被称为模块的独立文件中,模块是扩展名为.py的文件。若主程序需要用时,导入即可。

import 语句允许在当前运行的程序文件中导入模块中的函数。导入模块的方法有很多种,下面简单介绍一下:

1.导入整个模块

首先定义一个test01.py文件,定义函数如下:
test01.py

def person(name,age):
    print('my name is '+name+', my age is ' +age)

在test01.py所在的目录中创建另一个名为test02.py的文件,导入test01.py,并调用person函数,调用的格式为:导入的模块名称.函数名

import test01

test01.person('bob','30')
test01.person('lily','30')

输出如下:

E:\python\python.exe G:/PyProject/untitled/test02.py
my name is bob, my age is 30
my name is lily, my age is 30

Process finished with exit code 0

2.导入特定的函数

导入模块中的特定函数的语法如下:

from module_name import function_name

如果想导入多个函数,格式如下:

from module_name import function_0, function_1, function_2

在上一节中,我们可以在test02.py中导入时直接指定具体的函数,代码如下:

from test01 import person

person('bob','30')
person('lily','30')

执行结果如下:

E:\python\python.exe G:/PyProject/untitled/test02.py
my name is bob, my age is 30
my name is lily, my age is 30

Process finished with exit code 0

3.导入模块中所有的函数

使用星号(* )运算符可让Python导入模块中的所有函数。在test01.py增加一个函数,如下:

def person(name,age):
    print('my name is '+name+', my age is ' +age)

def student(id,classname):
    print(' id is ' + id + ', classname  is ' + classname)

在test02.py全部导入:

from test01 import *

person('bob','30')
student('lily','30')

import 语句中的星号让Python将模块test01中的每个函数都复制到这个程序文件中。由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。

然而,使用 并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函 数或变量,进而覆盖函数,而不是分别导入所有的函数。

4.使用as给函数指定别名

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名。要给函数指定这种特殊外 号,需要在导入时指定。语法如下:

from module_name import function_name as fn

例如在test02.py中:

from test01 import person as a

a('bob','30')

5.使用as给模块指定别名

也可以给模块指定别名,语法如下:

import module_name as mn

例如在test02.py中:只是模块名改变,但函数名没变,调用函数时还是用之前的名称

import test01 as p

p.person('bob','30')

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐