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

Oli*_*Oli 0 python datetime

我有一个方法:

def do_something(year=?, month=?):
    pass
Run Code Online (Sandbox Code Playgroud)

我希望yearmonth参数是可选的,但我希望它们的默认值等于当前年份和月份.我已经考虑过在方法声明之前设置两个变量,但是这个过程可以运行几个月.它需要是动态的.

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

Mar*_*off 8

这里惯用的方法是指定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...
Run Code Online (Sandbox Code Playgroud)

您可能认为可以这样做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
Run Code Online (Sandbox Code Playgroud)