Python datetime.now() 作为默认函数参数在不同时间返回相同的值

Ene*_*Boy 11 python python-3.x python-datetime

现在我遇到了一些无法解释和解决的问题。
这是我的第一个 python 模块

时间助手.py

from datetime import datetime

def fun1(currentTime = datetime.now()):
    print(currentTime)
Run Code Online (Sandbox Code Playgroud)

另一个是

主要.py

from TimeHelper import fun1
import time

fun1()
time.sleep(5)
fun1()
Run Code Online (Sandbox Code Playgroud)

当我运行 Main.py 时,输出是
2020-06-16 09:17:52.316714
2020-06-16 09:17:52.316714

我的问题是为什么结果中的时间会相同?将 datetime.now() 传递给默认参数时是否有任何限制?

Ene*_*Boy 12

我想我找到了答案。感谢@user2864740
所以我将 TimeHelper.py 更改为这个

from datetime import datetime

def fun1(currentTime = None):
    if currentTime is None:
        currentTime = datetime.now()
    print(currentTime)
Run Code Online (Sandbox Code Playgroud)

一切都符合我的期望。

  • 抱歉,我的不好,它会是“if not currentTime”,但使用“is”是很好的做法。 (2认同)

Sar*_*mar 5

这是因为当您定义函数 datetime.now() 时,仅在该时间求值,并且该值存储在 currentTime 中,因此每当您运行fun1 currentTime 值都不会更新。
你可以简单地在TimeHelper.py中执行此操作

from datetime import datetime

def fun1(currentTime=None):
    if currentTime:
        print(currentTime)
    else:
        print(datetime.now())
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :)