zoukankan      html  css  js  c++  java
  • 函数参数

    # 关键字参数
    def menu(wine, entree, dessert):
        print({'wine': wine, 'entree': entree, 'dessert': dessert})
    
    
    menu('frontenac', dessert='flan', entree='fish')
    # 指定默认参数值
    def menu(wine, entree, dessert='pudding'):
        print({'wine': wine, 'entree': entree, 'dessert': dessert})
    
    menu('chardonnay', 'chicken') # {'dessert': 'pudding', 'entree': 'chicken', 'wine': 'chardonnay'}
    
    def nonbuggy(arg, result=None):
        if result is None:
            result = []
        result.append(arg)
        print(result)
    
    nonbuggy('a') # ['a']
    nonbuggy('b') # ['b']
    # 使用*收集位置参数
    def print_args(*args):
        print(args)
    
    
    print_args(3, 2, 1, 'wait!', 'uh...')
    
    def print_more(required1, required2, *args):
        print('Need this one:', required1)
        print('Need this one too:', required2)
        print('All the rest:', args)
    
    print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
    
    #(3, 2, 1, 'wait!', 'uh...')
    #('Need this one:', 'cap')
    #('Need this one too:', 'gloves')
    #('All the rest:', ('scarf', 'monocle', 'mustache wax'))
    # 使用**收集关键字参数
    #使用两个星号可以将参数收集到一个字典中,
    #参数的名字是字典的键,对应参数的值是字 典的值
    def print_kwargs(**kwargs):
        print(kwargs)
    
    print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
    
    #{'dessert': 'macaroon', 'entree': 'mutton', 'wine': 'merlot'}

    关键词变量

    def get_log(user_id, log_id):
        print(user_id, log_id)
    
    get_log('1', '1')
    get_log(user_id='1', log_id='1')
    parts = {'user_id': '1', 'log_id': '1'}
    get_log(**parts) #等价get_log(user_id='1', log_id='1')
  • 相关阅读:
    HTTP协议基础
    MySQL必知必会总结(二)
    MySQL必知必会总结(一)
    微信小程序开发总结
    从零开始搭建物联网平台(8):邮箱通知服务
    使用CDN优化首页加载速度
    Django+Vue前后端分离项目的部署
    Docker命令
    Django中间件执行流程和CSRF验证
    golang 快速排序及二分查找
  • 原文地址:https://www.cnblogs.com/jzm17173/p/5207247.html
Copyright © 2011-2022 走看看