0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの可変引数

Posted at

はじめに

Pythonの関数で引数を可変にする方法をまとめる。

目次

  • タプルとして渡す
  • キーワード引数として渡す
  • 可変引数の宣言順番

タプルとして渡す

*argsとして引数を宣言すると、タプル型として可変引数を渡すことができる。例では*argsとしているが、*xyzのように任意の文字列にアスタリスクをつけるでも良い。

sample
def func(*args):
	print(type(args))
	for i in args:
		print(i)

func(1,2,3,4,'a','b','c')

# <class 'tuple'>
# 1
# 2
# 3
# a
# b
# c
# None #tuple型の最後はNone

戻る

キーワード引数として渡す

**kwargsとして引数を宣言すると、辞書型として可変引数を渡すことができる。例では**kwargsとしているが、**xyzのように任意の文字列にアスタリスクをつけるでも良い。また、**kwargsへ辞書型の引数を代入する場合は、**引数名として、引数にアスタリスク2回
付けて代入する。

sample
def func(**kwargs):
	print(type(kwargs))
	for k,v in kwargs.items():
		print(k,v)

func(a=1,b=2,c=3)
# <class 'dict'>
# a 1
# b 2
# c 3

d={'a':1,'b':2,'c':3}
func(**d)
# <class 'dict'>
# a 1
# b 2
# c 3

戻る

可変引数の宣言順番

宣言する引数の順番は固定引数→*args→**kwargsの順番にする必要がある。順番を間違えるとエラーとなる。

sample
def func(i,j,*args,**kwargs):
	print(i,j,args,kwargs)
func(100,'zzz',1,2,3,'a','b','c',a=1,b=2,c=3)
# 100 zzz (1, 2, 3, 'a', 'b', 'c') {'a': 1, 'b': 2, 'c': 3}


def func(i,*args,j,**kwargs):
	print(i,j,args,kwargs)
func(100,1,2,3,'a','b','c','zzz',a=1,b=2,c=3)
# TypeError: func() missing 1 required keyword-only argument: 'j'

def func(i,j,**kwargs,*args):
	print(i,j,args,kwargs)
func(100,'zzz',a=1,b=2,c=3,1,2,3,'a','b','c')
# SyntaxError: arguments cannot follow var-keyword argument

戻る

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?