zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Python] 模块与函数的导入

2023-09-11 14:22:54 时间

为了方便使用函数,我们可以将函数存储在称为模块的独立文件中,再将模块导入到主程序中,导入一个模块需要使用import语句

在Python中,一个.py文件就是一个模块,使用模块的好处在于能够提高代码的可维护性,还可以避免函数名和变量名的冲突,相同名字的函数和变量完全可以分别存在于不同的模块中

一个abc.py的文件就是一个名叫abc的模块,一个xyz.py的文件就是一个名叫xyz的模块 

模块是一组Python代码的集合,可以使用其他模块,也可以被其他模块使用 

提示Tips:自己创建模块时要注意命名,不能和Python自带的模块名称冲突,比如系统自带了sys模块,自己的模块就不可命名为sys.py,否则将无法导入系统自带的sys模块 

演示案例准备

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

# This is test01.py
def person(name):
    print('My name is ' + name)

def my_age(age):
    print('My age is ' + age)
    
def my_hometown(hometown):
    print('My hometown is from ' + hometown)

在test01.py所在的目录中创建另一个名为test02.py的文件

# This is test02.py
# We will demonstrate the code in this file.

1.导入某个模块

语法格式

import module_name

导入特定模块后,调用模块中的某个函数

moudle_name.function_name()

例如,在test02.py文件中导入模块test01,并分别调用person函数、age函数以及my_hometown函数

# This is test02.py
# We will demonstrate the code in this file.
import test01
# My name is Andy
test01.person('Andy')
# My age is 18
test01.my_age('18')
# My hometown is from Guangzhou
test01.my_hometown('Guangzhou')

2.导入模块中的特定函数

导入模块中某个函数的语法格式

from moudle_name import function_name

例如,在test02.py文件中导入模块test01中的person函数

# This is test02.py
# We will demonstrate the code in this file.
from test01 import person
# My name is Andy
person('Andy')

导入模块中多个函数的语法格式

# 将函数用逗号,隔开即可 
from module_name import function_0,function_1,function_2

例如,在test02.py文件中导入模块test01中的person函数、age函数以及my_hometown函数

# This is test02.py
# We will demonstrate the code in this file.
from test01 import person,my_age,my_hometown
# My name is Andy
person('Andy')
# My age is 18
my_age('18')
# My hometown is from Guangzhou
my_hometown('Guangzhou')

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

语法格式

# 使用星号*运算符可以让Python导入模块中的所有函数
from module_name import *

一般不建议使用这种导入方法, 因为模块较大时,导入数据过多很占内存、影响性能

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

使用as给模块指定别名

import module_name as m

提示Tips: 如果我们给模块起了别名,再调用模块函数的时候,就得用别名来调用函数

例如,在test02.py文件中导入模块test01,并给该模块起名为t1

# This is test02.py
# We will demonstrate the code in this file.
import test01 as t1
# My name is Andy
t1.person('Andy')

导入模块中的函数,使用as给这个函数起别名

from module_name import function_name as fn

module_name表示模块名

function_name表示函数名

fn表示给函数function_name起的别名 

为什么要给函数起别名? 

① 函数名称太长

② 导入的函数名和程序中现有名称一致 

例如,在test02.py文件中导入模块test01中的my_hometown函数,并为该函数起名为ht

# This is test02.py
# We will demonstrate the code in this file.
from test01 import my_hometown as ht
# My hometown is from Dalian
ht('Dalian')