LoginSignup
24
20

More than 3 years have passed since last update.

python *args, **kwargs 使い方メモ

Last updated at Posted at 2020-01-29

何ができるのか

いくつ来るか分からない引数をまとめて受け取れます。

位置引数

*args にtupleで入ります

python
def test(*args, **kwargs):
    print(args)
    print(kwargs)

test(1, 2, 'hoge')
output
(1, 2, 'hoge')
{}

キーワード引数

**kwargs にdict()で入ります。

python
def test(*args, **kwargs):
    print(args)
    print(kwargs)

test(1, 2, 3, 4, 5, col=4, row=5)
output
(1, 2, 3, 4, 5)
{'col': 4, 'row': 5}

該当する引数がない場合

空のtuple()と空のdict()になります。

python
def test(*args, **kwargs):
    print(args)
    print(kwargs)

test()
output
()
{}

**kwargsから値を受け取る

kwargs.get('hoge')とすると引数が渡されなかった場合はNone、引数が渡されている場合は値を受け取ることが出来ます。

python
def func(*args, **kwargs):
    print(kwargs.get('a'), kwargs.get('b'))

test(a=10)
test(b=123)
output
10 None
None 123

wrapper関数で使うと便利

受け取った引数をそのまま渡せちゃいます

python
def func1(a, b, c=2):
    d = a + b * c
    return d

def func2(*args, **kwargs):
    d = func1(*args, **kwargs)
    return d

print(func2(1, 2))
print(func2(1, 2, c=5))
output
5
11

引数名は変更できる

じつは * の数が同じなら引数名は自由に変更できます。argsの代わりに *a, *hogeなどでも良いし、*kwargsの代わりに **b, **fuga などでも同様に動きます。

python
def test(*a, **b):
    print(a)
    print(b)

test(1, 2, 3, 4, 5, col=4, row=5)
output
(1, 2, 3, 4, 5)
{'col': 4, 'row': 5}

レッツトライ!

24
20
1

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
24
20