次のメソッド定義では、*
と**
は何をしparam2
ますか?
def foo(param1, *param2):
def bar(param1, **param2):
次のメソッド定義では、*
と**
は何をしparam2
ますか?
def foo(param1, *param2):
def bar(param1, **param2):
*args
andは、Pythonドキュメントの関数の定義に関する**kwargs
セクションで詳しく説明されているように、関数に任意の数の引数を許可するための一般的なイディオムです。
は*args
、すべての関数パラメーターをタプルとして提供します。
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
は、辞書としての仮パラメータに対応するものを除いて、**kwargs
すべての
キーワード引数を提供します。
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27
両方のイディオムを通常の引数と組み合わせて、一連の固定引数といくつかの可変引数を許可できます。
def foo(kind, *args, **kwargs):
pass
これを逆に使用することも可能です。
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 lee
*l
このイディオムのもう1つの使用法は、関数を呼び出すときに引数リストを解凍することです。
def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
Python 3では*l
、割り当ての左側で使用することができます(Extended Iterable Unpacking)。ただし、このコンテキストではタプルの代わりにリストが表示されます。
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
また、Python 3は新しいセマンティクスを追加します(PEP 3102を参照)。
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
このような関数は3つの位置引数のみを受け入れ、それ以降はすべて*
キーワード引数としてのみ渡すことができます。
dict
キーワード引数の受け渡しに意味的に使用されるPythonは、任意の順序になっています。ただし、Python 3.6では、キーワード引数は挿入順序を記憶することが保証されています。**kwargs
順序は、キーワード引数が関数に渡された順序に対応しています。」-Python3.6の新機能*
また、関数を**
呼び出すときにも使用できることにも注意してください。これは、リスト/タプルまたはディクショナリのいずれかを使用して、関数に複数の引数を直接渡すことができるショートカットです。たとえば、次の関数がある場合:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
次のようなことができます。
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
注:のキーはmydict
、関数のパラメーターとまったく同じ名前にする必要がありますfoo
。それ以外の場合は、:をスローしTypeError
ます
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
単一の*は、任意の数の追加の位置引数が存在する可能性があることを意味します。foo()
のように呼び出すことができますfoo(1,2,3,4,5)
。foo()の本体では、param2は2〜5を含むシーケンスです。
二重**は、追加の名前付きパラメーターがいくつでも存在できることを意味します。bar()
のように呼び出すことができますbar(1, a=2, b=3)
。bar()の本体にあるparam2は、{'a':2、'b':3}を含む辞書です。
次のコードで:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
出力は
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
**
(二重星) と*
(星) はパラメーターに対して何をしますか?
関数を定義して受け入れ、ユーザーが任意の数の引数、位置 ( *
) およびキーワード ( ) を渡すことができるようにします**
。
*args
という名前のタプルに割り当てられる、任意の数のオプションの位置引数 (パラメーター) を許可しますargs
。
**kwargs
任意の数のオプションのキーワード引数 (パラメーター) を許可します。これは、 という名前の dict になりますkwargs
。
任意の適切な名前を選択できます (また選択する必要がありますargs
) kwargs
。
*args
また、 andを使用し**kwargs
て、それぞれリスト (または任意のイテラブル) および辞書 (または任意のマッピング) からパラメーターを渡すこともできます。
パラメータを受け取る関数は、それらが展開されていることを知る必要はありません。
たとえば、Python 2 の xrange は明示的に を想定していません*args
が、引数として 3 つの整数を取るためです。
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
別の例として、次のように dict 展開を使用できますstr.format
。
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
の後にキーワードのみの引数を指定できます*args
-たとえば、ここでは、kwarg2
位置的にではなく、キーワード引数として指定する必要があります:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
使用法:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
また、*
無制限の位置引数を許可せずに、キーワードのみの引数が続くことを示すために、単独で使用できます。
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
ここkwarg2
でも、明示的に名前が付けられたキーワード引数でなければなりません:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
また、次のものがないため、無制限の位置引数を受け入れることはできなくなりました*args*
。
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
繰り返しますが、より簡単に言えば、ここでkwarg
は位置ではなく名前で指定する必要があります。
def bar(*, kwarg=None):
return kwarg
この例では、kwarg
位置を渡そうとするとエラーが発生することがわかります。
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
kwarg
パラメータをキーワード引数として明示的に渡す必要があります。
>>> bar(kwarg='kwarg')
'kwarg'
*args
(通常は "star-args" と呼ばれます) と**kwargs
(星は "kwargs" と言うことで暗示することができますが、"double-star kwargs" で明示的に表現してください) は、*
and**
表記を使用するための Python の一般的なイディオムです。*foos
これらの特定の変数名は必須ではありません (たとえば、 andを使用できます**bars
) が、慣例からの逸脱は仲間の Python コーダーを激怒させる可能性があります。
通常、これらは、関数が何を受け取るか、渡す引数の数がわからない場合に使用します。また、すべての変数に個別に名前を付けると非常に面倒で冗長になる場合もあります (ただし、これは通常、明示的な暗黙的よりも優れています)。
例 1
次の関数は、それらの使用方法を説明し、動作を示します。b
名前付き引数は、前の 2 番目の位置引数によって消費されることに注意してください。
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) \n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
dict(**kwargs), kweg=kweg))
関数のシグネチャのオンライン ヘルプを で確認できますhelp(foo)
。
foo(a, b=10, *args, **kwargs)
でこの関数を呼び出しましょうfoo(1, 2, 3, 4, e=5, f=6, g=7)
これは次を印刷します:
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
例 2
を提供する別の関数を使用して呼び出すこともできますa
。
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100)
プリント:
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
例 3: デコレータでの実際の使用
わかりました。ユーティリティはまだ表示されていない可能性があります。したがって、差別化コードの前および/または後に冗長コードを持つ関数がいくつかあると想像してください。次の名前付き関数は、説明のための疑似コードにすぎません。
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
これを別の方法で処理できるかもしれませんが、デコレーターを使用して冗長性を確実に抽出できるため、以下の例は非常に役立つ方法*args
を示しています。**kwargs
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
そして、冗長性を取り除いたので、すべてのラップされた関数をより簡潔に書くことができます:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
そして、コードを除外することで*args
、**kwargs
コード行を削減し、可読性と保守性を向上させ、プログラム内のロジックの正規の場所を 1 つだけ持つことができます。この構造の一部を変更する必要がある場合、それぞれの変更を行う場所が 1 つあります。
まず、位置引数とキーワード引数とは何かを理解しましょう。以下は、位置引数を使用した関数定義の例です。
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
したがって、これは位置引数を持つ関数定義です。キーワード/名前付き引数でも呼び出すことができます:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
ここで、キーワード引数を使用した関数定義の例を調べてみましょう:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
位置引数を指定してこの関数を呼び出すこともできます。
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
これで、位置引数とキーワード引数を使用した関数定義がわかりました。
ここで、'*' 演算子と '**' 演算子について調べてみましょう。
これらの演算子は 2 つの領域で使用できることに注意してください。
a)関数呼び出し
b)関数定義
関数呼び出しでの「*」演算子と「**」演算子の使用。
例を見て、それについて議論しましょう。
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
だから覚えておいて
関数呼び出しで「*」または「**」演算子が使用されている場合-
'*' 演算子は、リストやタプルなどのデータ構造を関数定義で必要な引数にアンパックします。
'**' 演算子は、辞書を関数定義で必要な引数にアンパックします。
ここで、関数定義での「*」演算子の使用について調べてみましょう。例:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
関数定義では、'*' 演算子は受け取った引数をタプルにパックします。
関数定義で使用される '**' の例を見てみましょう。
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
関数定義では '**' 演算子は、受け取った引数を辞書にパックします。
だから覚えておいてください:
関数呼び出しでは、'*'は、タプルまたはリストのデータ構造を、関数定義によって受け取られる位置引数またはキーワード引数にアンパックします。
関数呼び出しでは、'**'は辞書のデータ構造を位置引数またはキーワード引数にアンパックし、関数定義で受け取ります。
関数定義では、「*」は位置引数をタプルにパックします。
関数定義では、'**' はキーワード引数を辞書にパックします。
*
**
関数の引数リストで特別な使用法があります。*
引数がリストで**
あることを意味し、引数が辞書であることを意味します。これにより、関数は任意の数の引数を取ることができます
Pythonドキュメントから:
仮パラメータースロットよりも多くの位置引数がある場合、構文「*識別子」を使用する仮パラメーターが存在しない限り、TypeError例外が発生します。この場合、その仮パラメーターは、過剰な位置引数を含むタプル(または、過剰な位置引数がなかった場合は空のタプル)を受け取ります。
キーワード引数が仮パラメータ名に対応していない場合、構文「**識別子」を使用する仮パラメータが存在しない限り、TypeError例外が発生します。この場合、その仮パラメーターは、過剰なキーワード引数を含むディクショナリ(キーワードをキーとして使用し、引数値を対応する値として使用)を受け取るか、過剰なキーワード引数がない場合は(新しい)空のディクショナリを受け取ります。
Python 3.5 では、この構文をlist
、dict
、tuple
、およびset
ディスプレイ (リテラルとも呼ばれます) でも使用できます。PEP 488: 追加のアンパックの一般化を参照してください。
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
また、1 回の関数呼び出しで複数のイテラブルをアンパックすることもできます。
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(PEP リンクの mgilson に感謝します。)
他の人が言及していない例を挙げたい
*ジェネレーターをアンパックすることもできます
Python3 ドキュメントの例
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x は [1, 2, 3]、unzip_y は [4, 5, 6] になります。
zip() は、複数の iretable 引数を受け取り、ジェネレーターを返します。
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
関数に渡された引数を、関数本体とその内部にそれぞれlist
パックします。dict
次のような関数シグネチャを定義すると:
def func(*args, **kwds):
# do stuff
任意の数の引数とキーワード引数で呼び出すことができます。非キーワード引数args
は関数本体内で呼び出されるリストにパックされ、キーワード引数は関数本体内で呼び出される dict にパックされkwds
ます。
func("this", "is a list of", "non-keyowrd", "arguments", keyword="ligma", options=[1,2,3])
関数本体の内部には、関数が呼び出されると、値を持つリストと値をargs
持つリストである2 つのローカル変数があります。["this", "is a list of", "non-keyword", "arguments"]
kwds
dict
{"keyword" : "ligma", "options" : [1,2,3]}
これは逆に、つまり呼び出し側からも機能します。たとえば、次のように定義された関数があるとします。
def f(a, b, c, d=1, e=10):
# do stuff
呼び出しスコープにあるイテラブルまたはマッピングをアンパックすることで、それを呼び出すことができます。
iterable = [1, 20, 500]
mapping = {"d" : 100, "e": 3}
f(*iterable, **mapping)
# That call is equivalent to
f(1, 20, 500, d=100, e=3)
関数呼び出しに加えて、*args と **kwargs はクラス階層で役立ち、__init__
Python でメソッドを記述する必要もありません。同様の使用法は、Django コードなどのフレームワークでも見られます。
例えば、
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
サブクラスは次のようになります
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
サブクラスは次のようにインスタンス化されます
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
また、そのサブクラス インスタンスに対してのみ意味を持つ新しい属性を持つサブクラスは、基本クラスを呼び出して__init__
属性設定をオフロードできます。これは、*args と **kwargs によって行われます。kwargs は主に、名前付き引数を使用してコードを読み取り可能にするために使用されます。例えば、
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
これは次のように設定できます
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
完全なコードはこちら
この例は、Python の、さらには継承を一度に覚える*args
のに役立ちます。**kwargs
super
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1