LoginSignup
22
16

More than 5 years have passed since last update.

[Python]関数引数の*(star)と**(double star)

Last updated at Posted at 2016-01-01

Pythonでは任意個の引数を受け取る関数を作る時に*か**を引数の前につける。

関数側から見ると*をつけるとTupleになり、**をつけるとDictionaryで受け取ることになる。
呼び出し側から見ると、Tupleで渡すときはKeyword無し、Dictionaryで渡すときはKeywordありにする。

def func1(*param1):
    print(param1)
def func2(**param1):
    print(param1)
In [3]: func1(1,2,3,4,5)
(1, 2, 3, 4, 5)

In [4]: func2(a=1,b=2,c=3,d=4,e=5)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

Unpacking Argument

tupleの中身をばらばらで渡したい時
func1(*t1)func1(0,1,2)の結果が同じになる。
Dictionaryの場合は**を使う。

In [13]: t1 =  (0,1,2)    

In [14]: func1(*t1)
(0, 1, 2)

In [15]: func1(0,1,2)
(0, 1, 2)

In [16]: func1(t1)
((0, 1, 2),)

詳細はここに書いてある。

22
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
16