前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

Python基础编程——函数参数

qiguaw 2024-11-19 09:09:46 资源文章 14 ℃ 0 评论

上一节我们介绍了函数的概念、作用以及如何定义函数,本节将介绍函数的重要内容——参数。参数对于一个函数来说不是必不可少的,但是其作用却很重要,因为参数给函数带来了灵活性,否则我们所编写的函数就只能返回固定的值,当用户需求变化时,函数并不能很好的满足需求。

参数分类

根据要求Python的规范以及调用函数时的实际使用情况,可以将函数的参数分为以下四类:

  1. 必需参数
  2. 关键字参数
  3. 默认参数
  4. 不定长度参数

每种类型的参数的用法都不尽相同,下面介绍各种参数的使用方法以及具体的含义。

注意:在def语句中,位于函数名后面的变量通常称为形参,而调用函数时提供的值称为实参在调用函数时,实参将会给行参传值,即用实参的值去替换行参

必需参数

必需参数也称之为位置参数,在定义函数与调用函数,它们都是必不可少的并且其在参数列表中的位置需要一一对应,否则将得不到我们想要的结果。具体用法如下must_parameter.py程序所示:

must_parameter.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 定义一个字典用于存放学生信息
students = {
    '20210001': {'name': '张三', 'city': '北京', 'age': 19},
    '20210002': {'name': '王五', 'city': '上海', 'age': 18},
    '20210003': {'name': '李四', 'city': '广州', 'age': 20}
}


# 定义一个函数,用于获取学生信息
def get_student_info(student_no, info_item):
    student_info = students.get(student_no, None)

    if student_info:
        student_info_item = student_info[info_item]
        print('student_info_item = {}'.format(student_info_item))
        return student_info_item
    else:
        print('没有找到该学号所对应的学生信息!')
        return None


get_student_info('20210001', 'name')
get_student_info('name', '20210001')

程序执行结果如下所示:
student_info_item = 张三
没有找到该学号所对应的学生信息!

在上面的程序中我们首先定义了一个用于存放学生信息的字典——students,然后定义一个用于获取指定学生信息的函数——get_student_info(student_no, info_item),函数将返回查询到的学生信息项,如果没有查询到函数将会提示‘没有找到该学号所对应的学生信息!’。我们在调用函数时,传入正确的student_no和item时即可返回获取到的信息,将student_no和item交换位置时,则无法获取到学生信息。

注意:必需参数很重要,也是我们在使用函数时需要经常使用的。

关键字参数

关键字参数和函数的调用关系非常紧密,在调用函数时使用关键字参数来确定传入的参数值。在使用关键字参数时允许函数调用时传入的参数顺序与函数定义时的参数顺序不一致,因为这时Python解释器会根据参数名进行自动匹配。具体用法如下keyword_parameter.py程序所示:

keyword_parameter.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

students = {
    '20210001': {'name': '张三', 'city': '北京', 'age': 19},
    '20210002': {'name': '王五', 'city': '上海', 'age': 18},
    '20210003': {'name': '李四', 'city': '广州', 'age': 20}
}


def get_student_info(student_no, info_item):
    student_info = students.get(student_no, None)
    if student_info:
        student_info_item = student_info[info_item]
        print('student_info_item = {}'.format(student_info_item))
        return student_info_item
    else:
        print('没有找到该学号所对应的学生信息!')
        return None

# 关键字参数
get_student_info(student_no='20210002', info_item='age')
get_student_info(info_item='age', student_no='20210002')

程序执行结果如下所示:
student_info_item = 18
student_info_item = 18

从上面的程序执行结果可以看出,在使用关键字参数后,调用函数时,可以随意交换参数的顺序,函数执行的结果是相同。

默认参数

默认参数即在调用函数时,如果没有指定参数的值,则使用默认的参数的,由于Python不会给变量默认值,因此在定义函数时,需要指定参数的默认值。具体用法如下default_parameter.py程序所示:

students = {
    '20210001': {'name': '张三', 'city': '北京', 'age': 19},
    '20210002': {'name': '王五', 'city': '上海', 'age': 18},
    '20210003': {'name': '李四', 'city': '广州', 'age': 20}
}


def get_student_info(student_no='20210001', info_item='name'):
    student_info = students.get(student_no, None)
    if student_info:
        student_info_item = student_info[info_item]
        print('student_info_item = {}'.format(student_info_item))
        return student_info_item
    else:
        print('没有找到该学号所对应的学生信息!')
        return None


# 使用默认参数形式调用函数
get_student_info()
# 使用必须参数方式调用函数
get_student_info('20210001', 'name')

程序执行结果如下所示:
student_info_item = 张三
student_info_item = 张三

上面的程序中,我们在定义函数时即指定了参数的默认值,在调用函数时并没有传入参数,这是函数将会使用我们定义函数时的参数的默认值。当然,我们也可以在调用函数时传入指定的参数值。

不定长度参数

有时候函数能处理的参数比我们定义函数时的参数个数更多,即我们定义的函数允许用户传入任意多个参数,这种参数我们称之为不定长度参数。不定长度的参数有两种定义方法,一种是在参数名前面加一个星号(*),另一种是在参数名前面加两个星号(**)。它们的区别在于传入的参数的形式不同,当使用一个星号时将以元组的形式传入,当使用两个星号时将以字典的形式传入。具体用法如下unknown_length_parameter.py程序所示:

unknown_length_parameter.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

students = {
    '20210001': {'name': '张三', 'city': '北京', 'age': 19},
    '20210002': {'name': '王五', 'city': '上海', 'age': 18},
    '20210003': {'name': '李四', 'city': '广州', 'age': 20}
}


def get_student_info(student_no, *info_item):
    print('info_item = {}'.format(info_item))
    info_items = list()
    info = students.get(student_no, None)

    if info:
        for item in info_item:
            student_info_item = info[item]
            info_items.append(student_info_item)

        return info_items
    else:
        return '没有找到该学号所对应的学生信息!'


student_info = get_student_info('20210001', 'name', 'age')
print('student_info = {}'.format(student_info))

print('=' * 50)


def another_get_student_info(student_no, **kwargs):
    info = students.get(student_no, None)
    kwargs_list = list(kwargs.values())
    info_list = list(info.values())

    print('info = {}'.format(info))
    print('kwargs = {}'.format(kwargs))

    if len(kwargs_list) == len([item for item in kwargs_list if item in info_list]):
        return info_list
    else:
        return '没有找到该学号所对应的学生信息!'


student_info = another_get_student_info('20210001', name='张三', age=19)
print('student_info = {}'.format(student_info))

程序执行结果如下所示:
info_item = ('name', 'age')
student_info = ['张三', 19]
==================================================
info = {'name': '张三', 'city': '北京', 'age': 19}
kwargs = {'name': '张三', 'age': 19}
student_info = ['张三', '北京', 19]

在上面的程序中我们定义了两个函数get_student_info()和another_get_student_info()来分别演示一个星号和两个星号时的参数情况。从函数执行的结果我们可以看出,一个星号时,参数以元组的形式传递给函数;两个型号时,参数以字典的形式传递给函数。

注意:在Python中函数的参数使用很灵活,不仅仅可以单独使用上面介绍的各种类型的参数,还可以将它们组合到一起来使用,但是要尽量遵循以下规则,以便提高代码的可读性。具体如下所示:

def function(必需参数, 关键字参数, 默认参数, 不定长度参数),即:必需参数在参数列表的首位,关键字参数在参数列表的第二位,默认参数在参数列表的第三位,不定长度参数在参数列表的第四位。

总结

本节介绍了函数的四种类型的参数以及它们的用法,需要注意的是多种类型的参数组合使用时,需要注意它们在参数列表中的位置。

下一节将会进一步介绍一些经典的函数,敬请关注!

如果有需要文中小程序的可以私信我哟!

创作不容易,还请喜欢的小伙伴请点关注、收藏!

欢迎大家转发、评论!

#Python基础##Python入门推荐##Python编程从入门到实践##Python入门#

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表