如何解决当列表/集合是函数的默认参数时,列表/集合中的值是否保留用于下一个函数调用?
在一个函数中,有一个参数是一个集合,默认情况下它是一个空集合。
奇怪的是,第二次调用它具有第一次的值。
我可以通过一个简单的电话确认这一点
>>> def afun(tset=set()):
... print("start:{}".format(tset))
... tset.add('a')
... print("after:{}".format(tset))
...
>>> afun()
start:set() #this is what we expect
after:{'a'}
>>> afun() #here,I call the function the second time
start:{'a'} #!! this is not what I expect. I assume each time this function is call,the set is empty
after:{'a'}
>>> afun()
start:{'a'}
after:{'a'}
>>> def bfun(blist=[]):
... print("startb:{}".format(blist))
... blist.append("b")
... print("after:{}".format(blist))
...
>>> bfun()
startb:[]
after:['b']
>>> bfun()
startb:['b'] # Same here,in the next call of this function,the blist is not empty.
after:['b','b']
>>> bfun()
startb:['b','b']
after:['b','b','b']
>>> def cfun(c=3):
... print("startc:{}".format(c))
... c=9
... print("after:{}".format(c))
...
>>> cfun()
startc:3
after:9
>>> cfun()
startc:3 # this is what I would expect: each time the function is called,the value is reset.
after:9
为什么这样?如果未给出该值,如何获得一个干净的值? (我需要一个递归调用的集合,并且该集合在第一层必须为空)
我想我必须删除“默认值”,并确保在第一级调用此函数时提供空值。但是我仍然不满意它的样子。
它在python 3.6.9中。
这个问题已经在这里有了答案: “Least Astonishment” and the Mutable Default Argument(31个答案) 这是一个长达11年的讨论,阅读很有趣!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。