*args 和 **kwargs 经常看到,但是一脸懵逼 ,今天终于有收获了

"""
python 函数的入参经常能看到这样一种情况 *args  或者是 **kwargs
       但是它们到底是啥意思呢?
       代码能说明一切
"""


def hello(*args, **kwargs):
    print(args)  # ('小明', 25, '男', '中国银行')
    print(kwargs)  # {}


hello('小明', 25, '', '中国银行')

print('*' * 50)


def hello(*args, **kwargs):
    print(args)  # ()
    print(kwargs)  # {'name': '小明', 'age': 25, 'gender': '男', 'company': '中国银行'}


hello(name='小明', age=25, gender='', company='中国银行')

print('*' * 50)


def hello(name, *args, **kwargs):
    '''
     将第一个入参映射到name头上去了
    :param name:
    :param args:
    :param kwargs:
    :return:
    '''
    print(name)  # 小光
    print(args)  # (40, '男', '中国银行')
    print(kwargs)  # {}


hello('小光', 40, '', '中国银行')



print('*' * 50)


def hello(name, *args, **kwargs):
    '''
     将第一个入参映射到name头上去了
    '''
    print(name)  # 小光
    print(args)  # (40, '男', '中国银行')
    print(kwargs)  # {}


hello(name='小光', 40, '', '中国银行')  # 这样编译都不会通过


print('*' * 50)


def hello(name, *args, **kwargs):
    '''
     将第一个入参映射到name头上去了
    '''
    print(name)  # 小光
    print(args)  # ()
    print(kwargs)  # {'age': 40, 'gender': '男', 'company': '中国银行'}


hello(name='小光', age = 40, gender= '', company = '中国银行')  # 要搞就只能这样搞

 

至于 ,如何灵活的使用,还有待于工作中的摸索.....

posted on 2019-12-13 23:01  显示账号  阅读(484)  评论(0编辑  收藏  举报