美文网首页
*args **kwargs

*args **kwargs

作者: 手捧樱花v | 来源:发表于2020-09-07 14:56 被阅读0次
def test_args(first, second, third, fourth, fifth):
    print 'First argument: ', first
    print 'Second argument: ', second
    print 'Third argument: ', third
    print 'Fourth argument: ', fourth
    print 'Fifth argument: ', fifth

# Use *args
args = [1, 2, 3, 4, 5]
test_args(*args)
# results:
# First argument:  1
# Second argument:  2
# Third argument:  3
# Fourth argument:  4
# Fifth argument:  5

# Use **kwargs
kwargs = {
    'first': 1,
    'second': 2,
    'third': 3,
    'fourth': 4,
    'fifth': 5
}

test_args(**kwargs)
# results:
# First argument:  1
# Second argument:  2
# Third argument:  3
# Fourth argument:  4
# Fifth argument:  5

args和*kwargs可以非常方便的定义函数,同时可以加强扩展性,以便日后的代码维护

相关文章

网友评论

      本文标题:*args **kwargs

      本文链接:https://www.haomeiwen.com/subject/jktlektx.html