<p>另一个答案中提到的<code>argparse</code>经常使用<code>kwargs</code>。它在处理大量可选参数时提供了很大的灵活性,但语法并不简单。您需要处理用户不提供值的情况。字典<code>get</code>很适合:</p>
<pre><code>In [241]: def func(**kwargs):
...: print(kwargs)
...: x = kwargs.get('x',0)
...: y = kwargs.get('y',0)
...: return x + y
...:
...:
In [242]: func(x=1, y=2)
{'x': 1, 'y': 2}
Out[242]: 3
In [243]: func(**{'x':1, 'y':2})
{'x': 1, 'y': 2}
Out[243]: 3
</code></pre>
<p>同时使用<code>if 'x' in kwargs:</code>或<code>for key in kwargs:</code></p>
<p>对于关键字参数,可以使用相同的<code>**dict</code>输入样式:</p>
<pre><code>In [244]: def func(x=0, y=2):
...: return x + y
In [245]: func(**{'x':1, 'y':2})
Out[245]: 3
</code></pre>
<p>您可以用以下方法解压<code>kwargs</code>:</p>
<pre><code>In [246]: def func(**kwargs):
...: x, y = kwargs.values()
...: return x + y
...:
In [247]: func(**{'x':1, 'y':2})
Out[247]: 3
</code></pre>
<p>但在这种情况下,您最好使用<code>*args</code>:</p>
<pre><code>In [248]: def func(*args):
...: x, y = args
...: return x + y
...:
In [249]: func(1,2)
Out[249]: 3
</code></pre>
<p><code>argparse.Namespace</code>的部分代码:</p>
<pre><code>class Namespace(_AttributeHolder):
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
</code></pre>
<p>这会将字典键转换为对象属性。<code>argparse</code>还注意到,您可以使用<code>vars(args)</code>转到另一个方向,从对象的属性获取字典。你知道吗</p>