Python引数

python-parameter.png

pythonの可変長引数

def hoge(*args, **kwargs):
    pass
  • *args….tuple型の変数
  • **kwargs….dict型の引数

1個も無しでもok

便利な辞書型引数

def func(*args, **kwargs):
    print "args=", args,
    print "kwargs=", kwargs
 
print "func(1,\"ABC\",[1,2,3]):"
func(1,"ABC",[1,2,3])
print""
print "func(a=123,b=\"ABC\",c=[4,5,6]):"
func(a=123,b="ABC",c=[4,5,6])
print""
print "func(1,\"ABC\",[1,2,3],a=123,b=\"ABC\",c=[4,5,6]):"
func(1,"ABC",[1,2,3],a=123,b="ABC",c=[4,5,6])

出力結果
func(1,"ABC",[1,2,3]):
args= (1, 'ABC', [1, 2, 3]) kwargs= {}

func(a=123,b="ABC",c=[4,5,6]):
args= () kwargs= {'a': 123, 'c': [4, 5, 6], 'b': 'ABC'}

func(1,"ABC",[1,2,3],a=123,b="ABC",c=[4,5,6]):
args= (1, 'ABC', [1, 2, 3]) kwargs= {'a': 123, 'c': [4, 5, 6], 'b': 'ABC'}

サポートサイト Wikidot.com