位置实参
调用函数时,必须将函数调用中的每一个实参都关联到函数定义中的一个形参,为此,最简单的的关联方式是基于实参的顺序。这种关联方式即为位置实参
def describe_pet(animal_type ,pet_name):
print("\n I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name)
describe_pet('dog','harry')
返回:
I have a dog.
My dog's name is harry
关键字实参
关键字实参是传递函数的名称-值对。名称和值在实参中就关联起来了,因此在想函数传递实参时就不会混淆。
describe_pet(animal_type='dog',pet_name='harry')
or
describe_pet(pet_name='harry',animal_type='dog')
输出的结果都是一样的
同一样的通过def describe_pet(animal_type ='dog',pet_name)
可将animal_type默认为dog
而如果描述的animal_type不是dog可以这样调用
describe_pet(animal_type='cat',pet_name='harry')
可选的实参
有时候,需要让实参变成可选,这样使用函数的人就只需要在必要时才提供额外的信息。
def get_formattes_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_formattes_name('jimi','hendrix')
print(musician)
musician=get_formattes_name('john','hooker','lee')
print(musician)
返回
Jimi Hendrix
John Lee Hooker
传递任意的实参
def making_pizza(*toppings):
print(toppings)
making_pizza('peppperont')
making_pizza('beef','mushroom')
返回
('peppperont',)
('beef', 'mushroom')
值得注意的是为了让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
任意数量的关键字实参
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_info=build_profile('a','b',location='c',field='d')
print(user_info)
{'first_name': 'a', 'last_name': 'b', 'location': 'c', 'field': 'd'}