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可以非常方便的定义函数,同时可以加强扩展性,以便日后的代码维护
网友评论