函数参数的使用

本文最后更新于:10 个月前

一,Python函数参数的使用

1.不可变参数

1.1 位置实参(参数顺序要一致)

def describe_pet(animal_type, pet_name):
   """显示宠物的信息"""
   print("\nI have a " + animal_type + ".")
   print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

在参数的顺序上,实参与位置参数要一致,不然会出现一些无法预料到错误。

1.2 关键字参数

def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
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(animal_type='dog', pet_name='willie')

关键字参数顺序可以改变,在没有默认值的情况下,必须提供全部的参数。

1.3 位置参数与关键字混用

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('wille',animal_type='dog')

关键字参数必须在位置参数之后

2.可变参数

1. 1使用任意数量的位置实参

def 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')

‘*’ 是分隔符,可变参数实际上是将其组装成元组

1. 2使用任意数量的关键字实参

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)

参数组合在实际书写中,需要遵循一定的顺序:
位置参数->默认参数->边长参数->关键字参数->命名关键字参数


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!