は、Pythonにおける関数の引数は、つまり、引数が割り当てられ、属性操作であります関数のローカル名前空間内の変数に渡します。 あなたはこのような宣言がある場合:
def some_func(pos_arg1, pos_arg2, kw_arg1=1, kw_arg2='test'):
print "postional arg 1 =", pos_arg1
print "postional arg 2 =", pos_arg2
print "keyword arg 1 =", kw_arg1
print "keyword arg 2 =", kw_arg2
位置引数は必須で、与えられた順に割り当てられますが、キーワード引数はオプションであり、任意の順序で呼び出すことができます - 省略し、名前のキーワード引数は宣言されたデフォルト値(この例では1と 'test')を仮定します。これまでのところ:
>>> some_func(1) # positional arguments are mandatory
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: some_func() takes at least 2 arguments (1 given)
>>> some_func(1, 2) # this is ok
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 1
keyword arg 2 = test
>>> some_func(1, 2, 3) # this is also ok, keyword args may work like positional
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 3
keyword arg 2 = test
>>> some_func(1, 2, 3, 4) # this is also ok, keyword args may work like positional
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 3
keyword arg 2 = 4
>>> some_func(1, 2, kw_arg2=3) # kyword arguments may be given in any order
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 1
keyword arg 2 = 3
あり、宣言されていない引数に問題がある:
>>> some_func(1, 2, 3, 4, 5)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: some_func() takes at most 4 arguments (5 given)
は、しかし、あなたは特別なフォーム*
と**
を使用して任意の数の引数を持つことができます。
>>> def some_func(pos_arg1, pos_arg2, *args, **kw_args):
... print "postional arg 1 =", pos_arg1
... print "postional arg 2 =", pos_arg2
... print "other positional orgs =", args
... print "other keyword args =", kw_args
...
>>> some_func(1, 2, 3, 4, 5) # any number of arguments
postional arg 1 = 1
postional arg 2 = 2
other positional orgs = (3, 4, 5)
other keyword args = {}
>>> some_func(1, 2, a=3, x=4, y=5) # * and ** are optional
postional arg 1 = 1
postional arg 2 = 2
other positional orgs =()
other keyword args = {'a': 3, 'x': 4, 'y': 5}
>>> some_func(1, 2, 'banana', 'orange', 'apple', a=3, x=4, y=5)
postional arg 1 = 1
postional arg 2 = 2
other positional orgs = ('banana', 'orange', 'apple')
other keyword args = {'a': 3, 'x': 4, 'y': 5}
>>>
*
引数は位置指定引数のタプルとして使用でき、**
はキーワード引数のdictになります。
すべてを組み合わせることはできますが、すべてのキーワード引数は、定位置引数の後に宣言する必要があり、すべての任意の引数は名前付き引数の後になければなりません。
ありがとうございます。 – Josh