学习笔记 | 2021-2-28

第8章 函数

8.1 定义函数

下面是一个打印问候语的简单函数,名为greet_user():

greeter.py

def greet_user():
	"""显示简单的问候语"""
	print("Hello!")
	
greet_user()

8.1.1 向函数传递信息

def greet_user(username):
	"""显示简单的问候语"""
	print("Hello, " + username.title() + "!")
	
greet_user('jesse')

8.1.2 形参和实参
略。

8.2 传递实参

鉴于函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序和形参的顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成;还可使用列表和字典。

8.2.1 位置实参

pets.py

def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
	
describe_pet('hamster', 'harry')

1.调用函数多次

def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
	
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

在函数中,可根据需要使用任意数量的位置实参,Python将按顺序将函数调用中的实参关联到函数定义中相应的形参。

2.位置实参的顺序很重要
使用位置实参来调用函数时,如果实参的顺序不正确,结果可能出乎意料,请确认函数调用中实参的顺序与函数定义中形参的顺序一致。

8.2.2 关键字实参

关键字实参是传递给函数的名称-值对。

def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
	
describe_pet(animal_type='hamster', pet_name='harry')

关键字实参的顺序无关紧要,因为Python知道各个值该存储到哪个形参中。下面两个函数调用是等效的:

describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

注意 使用关键字实参时,务必准确地指定函数定义中的形参名。

8.2.3 默认值

def describe_pet(pet_name, animal_type='dog'):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
	
describe_pet(pet_name='willie')

请注意,在这个函数的定义中,修改了实参的排列顺序。然而,Python依然将这个实参视为位置实参,因此如果函数调用中只包含宠物的名字,这个实参将关联到函数定义中的第一个形参。现在,使用这个函数的最简单的方式是,在函数调用中只提供小狗的名字:

describe_pet('willie')

由于没有给animal_type提供实参,因此Python使用默认值’dog‘。
如果要描述的动物不是小狗,可使用类似于下面的函数调用:

describe_pet(pet_name='harry', animal_type='hamster')

注意 使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参。这让Python依然能够正确地解读位置实参。

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

def describe_pet(pet_name, animal_type='dog'):

基于这种定义,在任何情况下都必须给pet_name提供实参;指定该实参时可以使用位置方式,也可以使用关键字方式。如果要描述的动物不是小狗,还必须在函数调用中给animal_type提供实参;同样,指定该实参时可以使用位置方式,也可以使用关键字方式。
下面对这个函数的所有调用都可行:

 # 一条名为Willie的小狗
 describe_pet('willie')
 describe_pet(pet_name='willie')

 # 一条名为Harry的仓鼠
 describe_pet('harry', 'hamster')
 describe_pet(pet_name='harry', animal_type='hamster')
 describe_pet(animal_type='hamster', pet_name='harry')

注意 使用哪种调用方式无关紧要,只要函数调用能生成你希望的输出就行。

8.2.5. 避免实参错误
略。

8.3 返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。

8.3.1 返回简单值

formatted_name.py

def get_formatted_name(first_name, last_name):
	"""返回整洁的姓名"""
	full_name = first_name + ' ' + last_name
	return full_name.title()
	
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

8.3.2 让实参变成可选的

def get_formatted_name(first_name, middle_name, last_name):
	"""返回整洁的姓名"""
	full_name = first_name + ' ' + middle_name + ' ' + last_name
	return full_name.title()
	
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)

为让中间名变成可选的,可给实参middle_name指定一个默认值——空字符串,并在用户没有提供中间名时不使用这个实参。为让get_formatted_name()在没有提供中间名时依然可行,可给实参middle_name指定一个默认值——空字符串,并将其移到形参列表的末尾:

def get_formatted_name(first_name, last_name, middle_name=''):
	"""返回整洁的姓名"""
	if middle_name:
		full_name = first_name + ' ' + middle_name + ' ' + last_name
	else:
		full_name = 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)

8.3.3 返回字典

函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。例如,下面的函数接受姓名的组成部分,并返回一个表示人的字典:

person.py

def build_person(first_name, last_name):
	"""返回一个字典,其中包含有关一个人的信息"""
	person = {'first': first_name, 'last': last_name}
	return person
	
musician = build_person('jimi', 'hendrix')
print(musician)

你可以轻松地扩展这个函数,使其接受可选值,如中间名、年龄、职业或你要存储的其他任何信息。例如,下面的修改让你还能存储年龄:

def build_person(first_name, last_name, age=''):
	"""返回一个字典,其中包含有关一个人的信息"""
	person = {'first': first_name, 'last': last_name}
	if age:
		person['age'] = age
	return person
	
musician = build_person('jimi', 'hendrix', age=27)
print(musician)

8.3.4 结合使用函数和while循环

greeter.py

def get_formatted_name(first_name, last_name):
	"""返回整洁的姓名"""
	full_name = first_name + ' ' + last_name
	return full_name.title()
	
# 这是一个无限循环!
while True:
	print("\nPlease tell me your name:")
	f_name = input("First name: ")
	l_name = input("Last name: ")
	
	formatted_name = get_formatted_name(f_name, l_name)
	print("\nHello, " + formatted_name + "!")

但这个while循环存在一个问题:没有定义退出条件。我们要让用户能够尽可能容易地退出,因此每次提示用户输入时,都应提供退出路径。每次提示用户输入时,都使用break语句提供了退出循环的简单途径:

def get_formatted_name(first_name, last_name):
	"""返回整洁的姓名"""
	full_name = first_name + ' ' + last_name
	return full_name.title()
	
while True:
	print("\nPlease 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("\nHello, " + formatted_name + "!")

8.4 传递列表

你经常会发现,向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)。

def greet_user(names):
	"""向列表中的每位用户都发出简单的问候"""
	for name in names:
		msg = "Hello, " + name.title() + "!"
		print(msg)
		
usernames = ['hannah', 'ty', 'margot']
greet_user(usernames)

8.4.1 在函数中修改列表

将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。

printing_models.py

# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
	current_design = unprinted_designs.pop()
	
	# 模拟根据设计制作3D打印模型的过程
	print("Printing model: " + current_design)
	completed_models.append(current_design)

# 显示打印好的所有模型
print("\nThe follwing 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()
		
		# 模拟根据设计制作3D打印模型的过程
		print("Printing model: " + current_design)
		completed_models.append(current_design)
		
def show_completed_models(completed_models):
	"""显示打印好的所有模型"""
	print("\nThe follwing models have been printed:")
	for completed_model in completed_models:
		print(completed_model)
		
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

描述性的函数名让别人阅读这些代码时也能明白,虽然其中没有任何注释。

8.4.2 禁止函数修改列表
要将列表的副本传递给函数,可以像下面这样做:

function_name(list_name[:])

切片表示法[:]创建列表的副本。在print_models.py中,如果不想清空未打印的设计列表,可像下面这样调用print_models():

print_models(unprinted_designs[:], completed_models)

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

8.5 传递任意数量的实参

pizza.py

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("\nMaking a pizza with the following toppings:")
	for topping in toppings:
		print("- " + topping)
	
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

不管函数收到的实参是多少个,这种语法都管用。

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

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
例如,如果前面的函数还需要一个表示比萨尺寸的实参,必须将该形参放在形参*toppings的前面:

def make_pizza(size, *toppings):
	"""概述要制作的比萨"""
	print("\nMaking a " + str(size) +
		"-inch pizza with the following toppings:")
	for topping in toppings:
		print("- " + topping)
	
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

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

user_profile.py

def build_profile(first, last, **user_info):
	"""创建一个字典,其中包含我们知道的有关用户的一切"""
	profile = {}
	profile['first_name'] = first
	profile['last_name'] = last
	for key, value in user_info.items():
		profile[key] = value
	return profile
	
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。

8.6 将函数存储在模块中

import语句允许在当前运行的程序文件中使用模块中的代码。

8.6.1 导入整个模块

pizza.py

def make_pizza(size, *toppings):
	"""概述要制作的比萨"""
	print("\nMaking a " + str(size) +
		"-inch pizza with the following toppings:")
	for topping in toppings:
		print("- " + topping)
making_pizzas.py

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

如果你使用这种import语句导入了名为module_name.py的整个模块,就可使用下面的语法来使用其中任何一个函数:
module_name.function_name()

8.6.2 导入特定的函数

from module_name import function_name
from module_name import function_0, function_1, function_2

8.6.3 使用as给函数指定别名

关键字as将函数重名为你提供的别名。指定别名的通用语法如下:

from module_name import function_name as fn

8.6.4 使用as给模块指定别名

import module_name as mn

8.6.5 导入模块中的所有函数

from pizza import *

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

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

from module_name import *

8.7 函数编写指南

应给函数指定描述性名称,且只在其中使用小写字母和下划线。
给形参指定默认值时,等号两边不要有空格:

def function_name(parameter_0, parameter_1='default value')
function_name(value_0, parameter_1='default value')

大多数编辑器都会自动对齐后续参数列表行,使其缩进程度与你给第一个参数列表行指定的缩进程度相同:

def function_name(
			parameter_0, parameter_1, parameter_2,
			parameter_3, parameter_4, parameter_5):
		function body...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值