python

传递任意数量的实参

2018-11-09  本文已影响6人  庵下桃花仙
# 8-12
def make_sandwich(*toppings):
    """打印三明治中添加的食材"""
    print(toppings)

make_sandwich('ham')
make_sandwich('ham', 'lettuce', 'beef')

# 8-13
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('Tao hua', 'xian',
                             school='guet',
                             profession='AI')
print(user_profile)

# 8-14
def make_car(manufacturer, model, **other):
    profile = {}
    profile['manufacturer'] = manufacturer
    profile['model'] = model
    for key, value in other.items():
        profile[key] = value
    return profile

car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
('ham',)
('ham', 'lettuce', 'beef')
{'first_name': 'Tao hua', 'last_name': 'xian', 'school': 'guet', 'profession': 'AI'}
{'manufacturer': 'subaru', 'model': 'outback', 'color': 'blue', 'tow_package': True}
上一篇下一篇

猜你喜欢

热点阅读