天天看點

python中*args **kwargs的使用

*args是非關鍵字參數,用于元組,**kwargs是關鍵字參數,用于字典。

1》*args

def show(*args):
    print type(args)
    print args
    for name in args:
        print name
        
show('song','python','c++','ping')#python将這些參數包裝成一個元組,傳給args
l=['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将這些參數包裝成一個字典,傳給kwargs
d={'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'}

------------------

(完)