• 技术文章 >Python技术 >Python基础教程

    Python如何传递任意数量的实参

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-07-01 10:01:47原创2228

    传递任意数量的实参

    形参前加一个 * ,Python会创建一个已形参为名的空元组,将所有收到的值都放到这个元组中:

    def make_pizza(*toppings):
        print("\nMaking a pizza with the following toppings: ")
        for topping in toppings:
            print("- " + topping)
    make_pizza('pepperoni')
    make_pizza('mushroom', 'green peppers', 'extra cheese')

    不管函数收到多少实参,这种语法都管用。

    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, 'mushroom', 'green peppers', 'extra cheese')

    运行结果:

    Making a 16-inch pizza with the following toppings: 
    - pepperoni
    Making a 12-inch pizza with the following toppings: 
    - mushroom
    - green peppers
    - extra cheese

    相关推荐:《Python视频教程

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

    def build_profile(first, last, **user_info):
        profile = dict()
        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='physic')
    print(user_profile)

    形参**user_info中的两个星号让python创建了一个名为user_info的空字典。

    专题推荐:python 传递实参
    上一篇:Python如何用json模块存储数据 下一篇:Python中的返回值是什么

    相关文章推荐

    • Python如何从文件中读取数据• Python如何用json模块存储数据

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网