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

标签 python datetime

我有一个方法:

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/

相关文章:

python - Matplotlib 在 X 和 Y 轴上指示点

c++ - 如何在 Cython 中使用 C++ operator[]?

python - 将值从屏幕管理器屏幕问题传递到字段

c# - C# 中的 DateTime.MinValue 与 new DateTime()

PHP DateTime 异常和错误处理

mysql - 如何将MySQL时间戳转换为带有时区的自定义格式?

python - 在 python 中调试 argparse

python - python 3.6 中的内联注释行为不同于 2.7

javascript - AJAX Date 无法正确显示日期

php - 字符串到 DateTime 对象