Python中关于“None”的问题请教
第一段代码
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 这个值具有什么特殊性么?谢谢
Python中关于“None”的问题请教
不要把一个 mutable 的对象作为参数默认值
在Python里,None 是个单例对象,表示“没有值”或者“空”。它跟 False、空列表 [] 或者 0 不是一回事,类型是 NoneType。
最常碰到的问题就是判断。别用 ==,直接用 is:
if x is None:
# 处理x为None的情况
if x is not None:
# 处理x不是None的情况
因为 is 比较的是对象标识(内存地址),对于 None 这个全局唯一实例,这么判断又快又准。
函数默认返回值就是 None,所以如果你写个函数没写 return,或者只写了 return,它返回的就是 None。有时候这会让调用方困惑,所以明确点更好。
另外,在可变默认参数那坑里,常用 None 来避免:
def func(items=None):
if items is None:
items = []
# ... 后续操作
这样每次调用,items 都是个新的空列表,不会出现多个调用共享同一个列表的诡异问题。
简单说,把 None 当成一个明确表示“空”或“无”的信号值来用,判断时用 is 就行。
Python 中的可变对象和不可变对象 https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference
除非是想曲线救国获得 static 变量
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
感觉学到了一点黑科技
这是一个经典错误,很多靠谱的 Python 书上都会讲解这个问题
可变对象和不可变对象的区别
千万不要把可变对象放在参数中
少加了两个字 默认

