Python学习笔记(七)
Aug 28, 2016
在函数中使用关键字实参时,关键字实参的顺序无关重要:
1
2
3
4
5
6
7
8
9
10def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name="harry", animal_type="hamster")
#
# I have a hamster.
# My hamster's name is Harry.
使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参,这让 Python 能够正确地解读位置参数:
1
2
3
4
5
6
7
8
9
10def 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('willie')
#
# I have a dog.
# My dog's name is Willie.使用 切片 禁止函数修改列表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27def 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 following 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)
print(unprinted_designs)
show_completed_models(completed_models)传递任意数量的实参:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17def 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')
#
# Making a pizza with the following toppings:
# - pepperoni
#
# Making a pizza with the following toppings:
# - mushrooms
# - green peppers
# - extra cheese形参名
*toppings
中的星号让 Python 创建一个名为toppings
的 空元组,并将收到的所有值都封装到这个元组中。如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17def 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')
# Making a 16_inch pizza with the following toppings:
# - pepperoni
#
# Making a 12_inch pizza with the following toppings:
# - mushrooms
# - green peppers
# - extra cheese使用任意数量的关键字实参:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15def 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)
# {'first_name': 'albert', 'field': 'physics',
# 'last_name': 'einstein', 'location': 'princeton'}形参
**user_info
中的两个星号让 Python 创建一个名为user_info
的空字典,并将收到的所有 名称-值 对都封装到这个字典中。使用
as
给函数、模块指定别名如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名——函数的另一名称,类似于外号:
1
2
3
4from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')你还可以给模块指定别名。通过给模块指定别名,让你能够更轻松地调用模块中的函数:
1
2
3
4import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')使用星号(
*
)运算符可让 Python 导入模块中的所有函数:1
2
3
4from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')使用并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果,Python 可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。
最佳的做法是,要么只导入你需要使用的函数,要么导入整个模块并用句点表示法。