请教一个关于“None”的问题

2017-07-26 20:29:04 +08:00
 saximi
第一段代码
def foo(bar=None):
print("bar=",bar) #语句 1
if bar is None:
bar=[]
bar.append("baz")
return bar

print("1:",foo())
print("2:",foo())
输出如下:
bar= None
1: ['baz']
bar= None
2: ['baz']


第二段代码
def foo(bar=[]):
print("bar=",bar) #语句 2
bar.append("baz")
return bar

print("1:",foo())
print("2:",foo())

输出如下:
bar= []
1: ['baz']
bar= ['baz']
2: ['baz', 'baz']

我可以理解的是,当默认参数初始值为[]时,每次进入函数体时,bar 值会发生变化。
但是我不理解的是,为何当默认参数 bar 初始值为 None 时会导致刚进入函数体时的 bar 值始终为 None ? None 这个值具有什么特殊性么?谢谢
1923 次点击
所在节点    Python
9 条回复
raptium
2017-07-26 20:42:34 +08:00
不要把一个 mutable 的对象作为参数默认值
Readme16
2017-07-26 21:19:25 +08:00
sagaxu
2017-07-26 21:24:04 +08:00
@raptium 除非是想曲线救国获得 static 变量
lxy
2017-07-26 21:44:14 +08:00
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “ pre-computed ” value is used for each call. This is especially important to understand when a default parameter is a mutable object...
https://docs.python.org/3/reference/compound_stmts.html
zhanglintc
2017-07-26 23:54:00 +08:00
感觉学到了一点黑科技
NoAnyLove
2017-07-27 00:19:48 +08:00
这是一个经典错误,很多靠谱的 Python 书上都会讲解这个问题
nongmei
2017-07-27 10:42:26 +08:00
可变对象和不可变对象的区别
zhusimaji
2017-07-27 18:37:26 +08:00
千万不要把可变对象放在参数中
zhusimaji
2017-07-27 18:39:40 +08:00
@zhusimaji 少加了两个字 默认

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/378181

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX