【问题标题】:Optional Parameters in Python with List Append [duplicate]Python中带有列表附加的可选参数[重复]
【发布时间】:2011-10-15 06:07:27
【问题描述】:

可能重复:
“Least Astonishment” in Python: The Mutable Default Argument

这很奇怪,当使用 .append() 方法时,Python 中的可选列表参数在函数调用之间是持久的。

def wtf(some, thing, fields=[]):
    print fields
    if len(fields) == 0:
        fields.append('hey');
    print some, thing, fields

wtf('some', 'thing')
wtf('some', 'thing')

输出:

[]
some thing ['hey']
['hey'] # This should not happen unless the fields value was kept
some thing ['hey']

为什么“fields”列表作为参数时包含“hey”?我知道它是本地作用域,因为我无法在函数之外访问它,但函数会记住它的值。

【问题讨论】:

    标签: python optional-parameters


    【解决方案1】:

    默认值只计算一次,因此使用可变类型作为默认值会产生意想不到的结果。你最好做这样的事情:

    def wtf(some, thing, fields = None):
      if fields is None:
        fields = []
    

    【讨论】:

    • 请注意,如果您致电 wtf('some', 'thing', something),这将无法拯救您。现在something 末尾多了一个"hey"
    • 怎么回事?如果“某物”是一个列表,那么它就不会是“无”,那么“字段”将等于“某物”,不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 2019-06-29
    • 1970-01-01
    • 2016-03-27
    • 2018-10-24
    相关资源
    最近更新 更多