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

我有一个方法:

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

https://stackoverflow.com/questions/3398562/

相关文章:

iphone - 如何确保浮点值始终是 0.25 的倍数?

ios-simulator - class_getClassMethod 通常返回 nil(似乎只适

php - 永久登录

iphone - CFBundleExecutable 错误

macos - 如何为 Mac OS X 制作可启动 DVD?

php - 使用php过滤掉数组中的重复值

objective-c - 如何将 self 作为方法参数传递?

c# - 使用 Web 应用程序管理定时事件的首选方法是什么?

.net - 来自非托管代码的 System.AccessViolationException?

vim - 如何指定文件的缩进?