参数
1. 关键字实参
通过关键字实参,函数可以不关心传参的顺序,代码如下:
先说一个反例,不用关键字传参,由于参数顺序的不同,导致传参错误。
#//不带关键字实参的函数,需要注意传参的顺序
def describe_pet1(animal_type, pet_name):
print('My ' + animal_type + ' is ' + pet_name)
describe_pet1('dog', 'Tony')
#//下面是一个错误的例子
def describe_pet2(animal_type, pet_name):
print('My ' + animal_type + ' is ' + pet_name)
describe_pet2('Tony', 'dog')
由于顺序不同,结果输出
My dog is Tony
My Tony is dog
下面这个是正确的案例
#//关键字实参
def describe_pet2(animal_type, pet_name):
print('My ' + animal_type + ' is ' + pet_name)
describe_pet2(animal_type = 'dog', pet_name = 'Tony')
由于传递的是关键字参数,所以结果为
My dog is Tony
2. 默认值
编写函数时,可以给参数设定默认值,调用函数的时候,就可以不用传递该参数。
传递默认值
注意:带默认值的参数要放在不带默认值的参数后面,否则会报错
def describe_pet3(pet_name, animal_type = 'dog'):
print('My ' + animal_type + ' is ' + pet_name)
describe_pet2(pet_name = 'Tony')
输出结果为
My dog is Tony
3. 在函数参数中传递列表
模仿打印机工作的案例
#//在函数中嵌套while循环,模拟打印机的未打印列表和已打印列表
def print_models(unprinted_models, completed_models):
#//用while循环,打印所有文件
while unprinted_models:
current_model = unprinted_models.pop()
#//模拟打印过程
print('print model: ' + current_model)
#//放入已打印列表
completed_models.append(current_model)
#//已完成列表展示函数
def show_completed_models(completed_models):
print('\nThe following models have been printed:')
for completed_model in completed_models:
print(completed_model)
unprinted_models = ['file1', 'file2', 'file3']
completed_models = []
print_models(unprinted_models, completed_models)
#//在上面的函数中,completed_models被永久改变了,这个是重点
show_completed_models(completed_models)
输出的结果为:
print model: file3
print model: file2
print model: file1
The following models have been printed:
file3
file2
file1
4. 传递任意数量的参数
在函数的形参前,加入*,参数变为可变长类型
展示动物园中的动物的案例
#//传递任意数量的实参的函数
def animalInZoo(*animals):
#//可以直接打印
print(animals)
def animalInAnotherZoo(*animals):
print('animalInAnotherZoo()')
#//可以用for循环的方式打印可变参数
for animal in animals:
print(animal)
# //调用函数
animalInZoo('dog', 'cat', 'wolf')
animalInAnotherZoo('dog', 'rat', 'tiger')
输出结果如下:
('dog', 'cat', 'wolf')
animalInAnotherZoo()
dog
rat
tiger
传递任意数量的关键字参数
在函数中,可以使用**,来传递任意数量的关键字参数,代码如下
#//传递任意数量的关键字实参(用**),参数传进来的是key-value对,最好用字典接受
def user_info(first, last, **info):
#创建一个字典,用于接受用户所有信息
user_info_dict = {}
#//把定长参数传进来
user_info_dict['first_name'] = first
user_info_dict['last_name'] = last
#//把不定长参数传进来
for key, value in info.items():
user_info_dict[key] = value
#//返回字典
return user_info_dict
#//调用函数,并接收返回值
result_dict = user_info('Ryan', 'Qing',
sex = 'male',
intrest = 'reading',
age = '29')
print(result_dict)
输出结果如下:
{'first_name': 'Ryan', 'last_name': 'Qing', 'sex': 'male', 'intrest': 'reading', 'age': '29'}