本篇博客为 python学习记录系列博客的 内容,欢迎访问 python速成博客导航:
👉不会吧,都2021年了还有人不会Python?三天急速入门教程!👈
一、关于函数的基本操作
- 关键字实参:
调用函数时,明确指出各个实参对应的形参,这样实参在括号内的位置就不重要了(否则与实参位置有关——也就是“位置实参”)
def describe_pet(pet_name, animal_type):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
# 以下两次调用等价
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
- 默认值:
编写函数时,可以给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。
注意:由于位置实参的原因,未指定默认值的形参要放在指定了默认值的形参之前!
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') # willie的种类是dog,便可以省略animal_type
describe_pet(pet_name='harry', animal_type='hamster') # 一只叫“harry”的仓鼠
- 返回简单值:使用return函数,同c/c++。
- 让实参变为可选的:
# 将middle_name指定默认值——空字符串
# Python将非空字符串解读为True,空字符串解读为False
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)
output:
Jimi Hendrix
John Lee Hooker
- 返回字典:
def build_person(first_name, last_name, age=''): # age作为可选实参
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age # 在这里判断赋值
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
- 传递列表(与c/c++逻辑相同):
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
- 如果想把列表传递到函数处理,又不想函数修改列表,可以使用副本:
fuben = yuanjian[:]
- 传递任意数量的实参:
*toppings中的星号让python创建一个名为toppings的空元组,并将接收到的所有值都封装到这个元组中。
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')
output:
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
- 结合位置实参使用任意数量实参:
结合使用时必须将接纳任意数量实参的形参放在最后。
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
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')
output:
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
- 使用任意数量的关键字实参:
# **user_info创建了一个名为user_info的空字典
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)
output:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
二、将函数存储在模块内
- 导入整个模块:
假如有一段python代码定义了一个名为make_pizza的函数,代码文件被命名为pizza.py;我们在该代码所在目录中创建另一个名为test.py的文件,这个文件导入刚创建的模块→impor pizza
,我们就可以使用pizza.py内的函数啦:
pizza.make_pizza()
- 导入特定的函数:
我们也可以只导入函数,还是拿pizza.py举例,我们可以这样导入:
from pizza import make_pizza
于是我们就可以直接用make_pizza()
函数了,且无需使用文件名+句点。 - 使用 as 给函数指定别名:
如果要导入的函数的名称可能与程序中现有的名称冲突;或者函数名称太长,那我们就可以给它起一个别名。
from pizza import make_pizza as mp
这样我们调用make_pizza函数可以简写成mp()
- 使用 as 给模块指定别名:
import pizza as p
于是调用函数也变得简单:
p.make_pizza()
- 导入模块中的所有函数:
from pizza import *
我们可以使用星号(*)导入模块中的所有函数。注意!最好不要这么做,因为你可能会遇到导入的函数、变量与现有工程中的重名的问题!
3、函数编写指南(一些建议):
- 应给函数指定描述性名称,且在其中使用小写字母和下划线;
- 每个函数都应包含简要地阐述其功能的注释(紧跟在函数定义后面),并采用文档字符串格式;
- 给形参指定默认值时,等号两边不要空格;
- 对于函数调用中的关键字实参,等号两边也不要空格;
- 如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开;
- 所有的import语句都应该放在文件的开头,除非文件的开头是描述整个程序的注释。