gpt4 book ai didi

python - 获取当前日期作为方法的默认参数

转载 作者:行者123 更新时间:2023-12-05 08:35:21 24 4
gpt4 key购买 nike

我有一个方法:

def do_something(year=?, month=?):
pass

我希望 yearmonth 参数是可选的,但我希望它们的默认值等于当前的年份和月份。我考虑过在方法声明之前设置两个变量,但这是其中一部分的过程可能会运行数月。它需要是动态的。

看起来应该不难,但我今天有精神障碍所以你会怎么做?

最佳答案

这里惯用的方法是将 None 指定为默认值,如果值仍然是 None,然后在方法内重新指定:

def do_something(year=None, month=None):
if year is None:
year = datetime.date.today().year
if month is None:
month = datetime.date.today().month

# do stuff...

您可能认为您可以执行 def do_something(year=datetime.date.today().year),但这会缓存值以便 year 会在对 do_something 的所有调用中都相同。

为了证明这个概念:

>>> def foo(x=time.time()): print x
...
>>> foo()
1280853111.26
>>> # wait a second at the prompt
>>> foo()
1280853111.26

关于python - 获取当前日期作为方法的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3398562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com