先上代码:
import datetime, time
def log(message, when=datetime.datetime.now()):
print(message, when)
log('hello once')
time.sleep(2)
log('hello twice')
>>>
hello once 2018-09-19 20:47:35.700265
hello twice 2018-09-19 20:47:35.700265
[Finished in 2.2s]
解释:
参数的默认值,会在每个模块加载进来时求出,而很多模块都是在程序启动时加载的。包含这段代码的模块一旦加载进来,参数的默认值就固定了。解决方法如题所示:
import datetime, time
def log(message, when=None):
if when == None:
when = datetime.datetime.now()
print(message, when)
log('hello once')
time.sleep(2)
log('hello twice')
>>>
hello once 2018-09-20 14:16:28.560857
hello twice 2018-09-20 14:16:30.561830
[Finished in 2.2s]
要点
- 对于以动态值作为默认值的关键字参数来说,应把形式上的默认值写为None,并在函数的文档字符串里面描述。