Python备忘录

持续更新的Python备忘录

记录一些我在学习和使用Python的过程中的一些小tips,此篇博客会长期更新

1. Python中的args 和 *kwargs

*args 是可选参数
**kwargs 也是可选参数,但如其名字中的kw:其传参时需要以键值对的形式传参
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
← 上一篇 没有啦~
Comments

添加新评论