Python 函数|Python 主题月

本文正在参加「Python主题月」,详情查看 活动链接

函数是带名字的代码块,用于完成具体的工作。要执行函数定义的特定任务,可调用该函数。通过使用函数,程序编写、阅读、测试和修复起来都更加容易。

定义函数

  • 下面是一个打印问候语的简单函数,名为 greet_user()
def greet_user():
    """显示简单的问候语。"""
    print("Hello!")

greet_user()
复制代码

向函数传递信息

def greet_user(username):
    """显示简单的问候语。"""
    print(f"Hello, {username}")

greet_user("jesse")
复制代码

实参和形参

  • 在函数 greet_user() 的定义中,变量 username 是一个形参(parameter),即函数完成工作所需的信息。
  • 在代码 greet_user('jesse') 中,值 jesse 是一个实参(argument),即调用函数时传递给函数的信息。

传递实参

  • 向函数传递实参的方式很多:可使用位置实参,这要求实参的顺序与形参的顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成;还可使用列表和字典。

位置实参

  • 用函数时,Python 必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式称为位置实参
def describe_pet(animal_type, pet_name):
    """显示宠物信息。"""
    print(f"I have a {animal_type}。")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet('hamster', 'harry')
复制代码
  1. 多次调用函数
    • 可以根据需要调用函数任意次。
  2. 位置实参的顺序很重要
    • 使用位置实参来调用函数时,如果实参的顺序不正确,结果可能出乎意料。
    • 函数调用中实参的顺序与函数定义中形参的顺序一致。

关键字实参

  • 关键字实参是传递给函数的名称值对。
  • 为直接在实参中将名称和值关联起来,所以向函数传递实参时不会混淆。
def describe_pet(animal_type, pet_name):
    """显示宠物信息。"""
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(animal_type='hamster', pet_name='harry')
复制代码
  • 关键字实参的顺序无关紧要,因为 Python 知道各个值该赋给哪个形参。

默认值

  • 编写函数时,可给每个形参指定默认值
  • 在调用函数中给形参提供了实参时,Python 将使用指定的实参值;否则,将使用形参的默认值。
def describe_pet(pet_name, animal_type='dog'):
    """显示宠物信息。"""
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(pet_name='harry')
复制代码

等效的函数调用

  • 鉴于可混合使用位置实参、关键字实参和默认值,通常有多种等效的函数调用方式。

避免实参错误

  • 你提供的实参多于或少于函数完成工作所需的信息时,将出现实参不匹配错误。

返回值

  • 函数并非总是直接显示输出,它还可以处理一些数据,并返回一个或一组值。
  • 函数返回的值称为返回值
  • 在函数中,可使用 return 语句将值返回到调用函数的代码行。

返回简单值

  • 下面来看一个函数,它接受名和姓并返回整洁的姓名:
def get_formatted_name(first_name, last_name):
    """返回整洁的姓名。"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)
复制代码

让实参变成可选的

  • 有时候,需要让实参变成可选的,这样使用函数的人就能只在必要时提供额外的信息。
  • 可使用默认值来让实参变成可选的。
def get_formatted_name(first_name, last_name, middle_name=''):
    """返回整洁的姓名。"""
    if middle_name:
        full_name = f"{first_name} {middle_name} {last_name}"
    else:
        full_name = f"{first_name} {last_name}"
    
    return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
复制代码

返回字典

  • 函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
def build_person(first_name, last_name):
    """返回一个字典,其中包含有关一个人的信息。"""
    person = {'first': first_name, 'last': last_name}

    return person

musician = build_person('jimi', 'hendrix')
print(musician)
复制代码

结合使用函数和 while 循环

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名。"""
    full_name = f"{first_name} {last_name}"
    
    return full_name.title()

while True:
    print("Please tell me your name:")
    print("(Enter 'q' at any time to quit)")

    f_name = input("First name: ")
    if f_name == 'q':
        break
    l_name = input("Last name: ")
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name, l_name)
    print(f"Hello, {formatted_name}!")
复制代码

传递列表

  • 将列表传递给函数后,函数就能直接访问其内容。
def greet_users(names):
    """向列表中的每位用户发出简单的问候。"""
    for name in names:
        msg = f"Hello, {name.title()}!"
        print(msg)

usernames = ['hannah', 'ty', 'margot']

greet_users(usernames)
复制代码

在函数中修改列表

  • 将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量数据。
  • 先看一个不使用函数的情况:
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']

completed_models = []

while unprinted_designs:
    current_design = unprinted_designs.pop()
    print(f"Printing model: {current_design}...")
    completed_models.append(current_design)

print("The following models have been printed:")

for completed_model in completed_models:
    print(completed_model)
复制代码
  • 再重新组织代码,加入函数
def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止。
    打印每个设计后,都将其移到列表 completed_models 中。
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"Printing model: {current_design}...")
        completed_models.append(current_design)

def show_completed_models(completed_models):
    """显示打印好的所有模型。"""
    print("The following models have been printed:")

    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']

completed_models = []

print_models(unprinted_designs, completed_models)

show_completed_models(completed_models)
复制代码
  • 该程序还演示了这样一种理念:每个函数都应只负责一项具体的工作。

禁止函数修改列表

  • 有时候,需要禁止函数修改列表。
  • 向函数传递列表的副本而非原件,这样,函数所做的修改都只影响副本,而原件丝毫不受影响。
  • 要将列表的副本传递给函数,可以像下面这样做:
function_name(list_name[:])
复制代码
  • 切片表示法创建列表的副本。

虽然向函数传递列表的副本可保留原始列表的内容,但除非有充分的理由,否则还是应该将原始列表传递给函数。这是因为让函数使用现成的列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。

传递任意数量的实参

  • 有时候,预先不知道函数需要接受多少个实参,好在 Python 允许函数从调用语句中收集任意数量的实参。
def make_pizza(*toppings):
    """打印顾客点的所有配料。"""
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
复制代码
  • 形参名 *toppings 中的星号让 Python 创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。
  • 现在,可以将函数调用 print() 替换为一个循环,遍历配料列表并对顾客点的比萨进行描述:
def make_pizza(*toppings):
    """概述要制作的披萨。"""
    print("Making a pizza with the following toppings:")
    
    for topping in toppings:
        print(f"- {topping}")

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
复制代码

结合使用位置实参和任意数量实参

  • 如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python 先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
  • 例如,还需要表示披萨的尺寸:
def make_pizza(size, *toppings):
    """概述要制作的披萨。"""
    print(f"Making a {size}-inch pizza with the following toppings:")
    
    for topping in toppings:
        print(f"- {topping}")

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
复制代码

使用任意数量的关键字实参

  • 有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。
  • 在这种情况下,可将函数编写成能够接受任意数量的键值对——调用语句提供了多少就接受多少。
def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    user_info['first_name'] = first
    user_info['last_name'] = last

    return user_info

user_profile = build_profile('albert', 'einstein',
                            location = 'princeton',
                            field = 'physics')
print(user_profile)
复制代码
  • 形参 **user_info 中的两个星号让 Python 创建一个名为 user_info 的空字典,并将收到的所有名称值对都放到这个字典中。

注意,你经常会看到形参名 **kwargs,它用于收集任意数量的关键字实参。

将函数存储在模块中

  • 使用函数的优点之一是可将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解得多。你还可以更进一步,将函数存储在称为模块的独立文件中,再将模块导入到主程序中。
  • import 语句允许在当前运行的程序文件中使用模块中的代码。
  • 通过将函数存储在独立的文件中,可隐藏程序代码的细节,将重点放在程序的高层逻辑上。这还能让你在众多不同的程序中重用函数。
  • 将函数存储在独立文件中后,可与其他程序员共享这些文件而不是整个程序。知道如何导入函数还能让你使用其他程序员编写的函数库。

导入整个模块

  • 要让函数是可导入的,得先创建模块。
  • 模块是扩展名为 .py 的文件,包含要导入到程序中的代码。
  • 首先创建一个模块 pizza.py
# pizza.py

def make_pizza(size, *toppings):
    """概述要制作的披萨。"""
    print(f"Making a {size}-inch pizza with the following toppings:")
    
    for topping in toppings:
        print(f"- {topping}")
复制代码
  • 其次在 making_pizza.py 中导入这个文件:
# making_pizza.py

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
复制代码

导入特定函数

  • 可以从指定模块中导入特定函数
# making_pizza.py

from pizza import make_pizza

make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
make_pizza(16, 'pepperoni')
复制代码

使用 as 给函数指定别名

  • 关键字 as 将函数重命名为指定的别名:
# making_pizza.py

from pizza import make_pizza as mp

mp()(12, 'mushrooms', 'green peppers', 'extra cheese')
mp(16, 'pepperoni')
复制代码

使用 as 给模块指定别名

# making_pizza.py

import pizza as p

p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
p.make_pizza(16, 'pepperoni')
复制代码

导入模块中的所有函数

  • 使用星号 * 运算符可让 Python 导入模块中的所有函数:
# making_pizza.py

from pizza import *

make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
make_pizza(16, 'pepperoni')
复制代码
  • 使用并非自己编写的大型模块时,最好不要采用这种导入方法。这是因为如果模块中有函数的名称与当前项目中使用的名称相同,可能导致意想不到的结果:Python 可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。
  • 最佳的做法是,要么只导入需要使用的函数,要么导入整个模块并使用句点表示法。

函数编写指南

  • 应给函数指定描述性名称,且只在其中使用小写字母下划线
  • 给模块命名时,也应该遵循上述约定。
  • 每个函数都应该包含简要地阐述其功能的注释。
  • 注释应该紧跟在函数定义后面,并采用文档字符串格式。
  • 给形参指定默认值时,等号两边不要有空格;对于函数调用中的关键字实参,也应遵循这种约定。
  • 所有 import 语句都应放在文件开头。除了在文件开头使用了注释来描述整个程序。
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享