【发布时间】: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