zoukankan      html  css  js  c++  java
  • *args和**kwargs用法

    '''
    @Date: 2019-10-10 21:14:56
    @LastEditors: 冯浩
    @LastEditTime: 2019-10-20 22:38:16
    '''
    
    def func(*args):
        # just use "*" to collect all remaining arguments into a tuple
        # 这里的*是关键符号,args可以替换为其他命名
        # 更一般的函数定义方式是def fun(*args,**kwargs),
        # 可以在许多Python源码中发现这种定义,
        # 其中*args表示任何多个无名参数,它本质是一个元组tuple;
        # **kwargs表示关键字参数,它本质上是一个字典dict。
        numargs = len(args)
        print("参数数量: {0}".format(numargs))
        for i, x in enumerate(args):
            print("参数 {0} 是: {1}".format(i, x))
        print()
    
    
    func('a', 'b', 'c', {1: 'one', 2: 'two'})
    func(('a', 'b', 'c'))
    func(['1', '2', '3'])
    print('-'*32)
    
    '''
    参数数量: 4
    参数 0 是: a
    参数 1 是: b
    参数 2 是: c
    参数 3 是: {1: 'one', 2: 'two'}
    
    参数数量: 1
    参数 0 是: ('a', 'b', 'c')
    
    参数数量: 1
    参数 0 是: ['1', '2', '3']
    
    '''
    
    def func_dict(**kwargs):
        print('传入参数长度为{0}, 类型为{1}, 内容为{2}'.format(
            len(kwargs), type(kwargs), kwargs)
        )
        for key,value in kwargs.items():
            print('键: {0}, 值: {1}'.format(key,value))
    
    
    # 注意这里变量不能为数字,但是字典可以.
    # 如1='one'不被允许
    func_dict(one='', two='')
    
    '''
    传入参数长度为2, 类型为<class 'dict'>, 内容为{'one': '一', 'two': '二'}
    键: one, 值: 一
    键: two, 值: 二
    
    '''
  • 相关阅读:
    git diff的使用
    composer安装特别慢的解决方案
    laravel5.5 excel的安装和使用
    laravel中有条件使用where
    数据结构10——强连通
    数据结构9——桥
    数据结构8——割点
    数据结构7——费用流
    数据结构6——网络流
    数据结构5——二分图匹配
  • 原文地址:https://www.cnblogs.com/feng-hao/p/11650685.html
Copyright © 2011-2022 走看看