跳到主要内容

8. 函数

定义函数

函数是带名字的代码块,使用关键词 def 定义

def greet_user():
"""显示简单的问候语"""
print('Hello')
greet_user()
  • def 定义函数,括号内可以包含多个参数,也可以不包含参数
  • 三引号注释,称为文档字符串,描述函数是做什么的,文档字符串用于自动生成有关程序中函数的文档

传递实参

  • 位置实参
  • 关键字实参
def describe_pet(animal_type, pet_name):
"""显示宠物信息"""
print(f'\nI have a {animal_type}')
print(f'My {animal_type}\'s name is {pet_name}')
describe_pet('cat', 'tom')
describe_pet(animal_type='dog', pet_name='jerry')
  • 默认值
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物信息"""
print(f'\nI have a {animal_type}')
print(f'My {animal_type}\'s name is {pet_name}')
describe_pet('jerry')
  • 等效的函数调用
# 一条名为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')

返回值

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 greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = f'Hello, {name.title()}!'
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

传递任意数量的实参

def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中

  • 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
"""概述要制作的披萨"""
print(f'\nMaking 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):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
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的空字典,并将收到的所有名称-值对都封装到这个字典中

将函数存储在模块中

  • 导入整个模块
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
  • 导入特定的函数
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
  • 使用as给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
  • 使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
  • 导入模块中的所有函数
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

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