【问题标题】:How can I create default keyword arguments for a variadic function?如何为可变参数函数创建默认关键字参数?
【发布时间】:2019-10-25 20:07:47
【问题描述】:

假设我们有一个可变参数函数,例如:

def oofay(*args, **kwargs):
    return "\u2609_\u2609"

我们如何为关键字参数“汉堡”设置默认值?

一种解决方法如下:

def oofay(*args, **kwargs):
    kwargs.setdefault("hamburg", 99000)
    return "\u2609_\u2609"

但是,我想要在定义时间而不是调用时间评估的默认参数。

考虑以下示例:

color = "white"
get_fleece_color = lambda shoop: shoop + ", whose fleece was as " + color + " as snow."

print(get_fleece_color("Igor"))

# [... many lines of code later...]

color = "pink polka-dotted"
print(get_fleece_color("Igor's cousin, 3 times removed"))

输出是:

Igor, whose fleece was white as snow.
Igor's cousin, 3 times removed Igor, whose fleece was as pink polka-dotted as snow.

我们不想在可变参数函数oofay 中出现粉红色圆点。那么....我们该怎么做呢?

【问题讨论】:

  • def oofay(*args, hamburg=99000, **kwargs): ...?
  • 只要把hamburg=99000 放在函数签名中,我错过了什么?

标签: python python-3.x variadic-functions default-arguments


【解决方案1】:

归功于Azatwim

def oofay(*args, hamburg=99000, **kwargs):
    return "\u2609_\u2609"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2011-08-21
    • 2021-08-22
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    相关资源
    最近更新 更多