这一段python程序,为什么结果是这样的

GCC-pig 2014-04-22 11:41:28
def saver(x=[]):
x.append(1)
print(x)
saver([2])
saver()
saver()
saver()


结果
[2, 1]
[1]
[1, 1]
[1, 1, 1]
...全文
153 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hw7be 2014-04-22
  • 打赏
  • 举报
回复
直接copy官方手册内容如下,链接https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))
This will print

[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
mohuanlun 2014-04-22
  • 打赏
  • 举报
回复
命名冲突,X就是个变量

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧