在Python中处理默认参数的最佳方法是什么?

boa*_*der 8 python

我有一些代码(其他人写的):

def render(self, name, value, attrs=None):
    if not attrs:
        attrs = {}
    attrs.update({'class': 'ui-autocomplete-input'})
Run Code Online (Sandbox Code Playgroud)

我认为可以重写为:

def render(self, name, value, attrs={}):
    attrs.update({'class': 'ui-autocomplete-input'})
Run Code Online (Sandbox Code Playgroud)

如果有人入境,这当然会失败attrs=None,但这是否值得期待?attrs={} (额外浪费的dict创作?)是否会受到惩罚?

我仍然对python很新,无法回答这些问题,但我很好奇.

当我在口译员中测试这个时,我得到:

>>> def x(attrs={}):
...   attrs.update({'a': 'b'})
...   print attrs
... 
>>> x({'b': 'c'})
{'a': 'b', 'b': 'c'}
>>> x({'d': 'e'})
{'a': 'b', 'd': 'e'}
>>> x()
{'a': 'b'}
Run Code Online (Sandbox Code Playgroud)

这怎么会导致问题?请注意,我总是将该dict添加到attrs,即使用户指定了一个(实际上可能指向一个不同的问题(我应该将class属性与现有的属性合并).

-------------------并指出上述缺陷------------------

>>> def yikes(attrs):
...   attrs.update({'something': 'extra'})
...   print attrs
>>> def x(attrs={}):
...   print "Before:", attrs
...   attrs.update({'a': 'b'})
...   print "After:", attrs
...   yikes(attrs)

>>> x({"b": "c"})
Before: {'b': 'c'}
After: {'a': 'b', 'b': 'c'}
{'a': 'b', 'b': 'c', 'something': 'extra'}
>>> x()
Before: {}
After: {'a': 'b'}
{'a': 'b', 'something': 'extra'}
Run Code Online (Sandbox Code Playgroud)

似乎还可以,问题是什么?

>>> x()
Before: {'a': 'b', 'something': 'extra'}
After: {'a': 'b', 'something': 'extra'}
{'a': 'b', 'something': 'extra'}
Run Code Online (Sandbox Code Playgroud)

啊,现在我明白了,如果{'something': 'extra'}被其他一些代码添加,那就永远不会被清理干净了.当然,我强迫那里的人都在那里,但那{'something': 'extra'}不应该是.这是一个微妙的足以成为混淆比赛的好饲料,了望PERL!

Ger*_*rat 13

使用attrs = {}的函数签名会咬你,因为它会继续连续调用该函数它的价值.原始代码是最好的.

例如.

>>> def a(attrs= {}):
...   print attrs
...   attrs.update({1:1})
...
>>> a()
{}
>>> a()
{1: 1}
Run Code Online (Sandbox Code Playgroud)

请注意它在第二次调用时如何保持第一次分配的值.