本文共 1649 字,大约阅读时间需要 5 分钟。
*args是非关键字参数,用于元组,**kwargs是关键字参数,用于字典。1》*args
def show(*args): print type(args) print args for name in args: print name show('song','python','c++','ping')#python将这些参数包装成一个元组,传给argsl=['song','python','c++','ping']show(*l)show(*('song','python','c++','ping'))结果: <type 'tuple'> ('song', 'python', 'c++', 'ping') song python c++ ping <type 'tuple'> ('song', 'python', 'c++', 'ping') song python c++ ping <type 'tuple'> ('song', 'python', 'c++', 'ping') song python c++ ping
2》**kwargs
def show(**kwargs): print type(kwargs) print kwargs print kwargs.items() for item in kwargs.items(): print item show(name='song',age=26,sex='man')#python将这些参数包装成一个字典,传给kwargsd={'name':'song','age':26,'sex':'man'}show(**d)结果: <type 'dict'> {'age': 26, 'name': 'song', 'sex': 'man'} [('age', 26), ('name', 'song'), ('sex', 'man')] ('age', 26) ('name', 'song') ('sex', 'man') <type 'dict'> {'age': 26, 'name': 'song', 'sex': 'man'} [('age', 26), ('name', 'song'), ('sex', 'man')] ('age', 26) ('name', 'song') ('sex', 'man')
3》*args和**kwargs混合使用
def foo(arg,*args, **kwargs): print 'arg = ',arg print 'args = ', args print 'kwargs = ', kwargs print '------------------'if __name__ == '__main__': foo(1,2,3) foo(1,a=1,b=2,c=3) foo(1,2,3,4, a=1,b=2,c=3) foo(1,'a', 1, None, a=1, b='2', c=3)结果: arg = 1 args = (2, 3) kwargs = {} ------------------ arg = 1 args = () kwargs = {'a': 1, 'c': 3, 'b': 2} ------------------ arg = 1 args = (2, 3, 4) kwargs = {'a': 1, 'c': 3, 'b': 2} ------------------ arg = 1 args = ('a', 1, None) kwargs = {'a': 1, 'c': 3, 'b': '2'} ------------------
(完)
转载地址:http://ojyai.baihongyu.com/