指定默认参数的惯用方式,其存在/不存在很重要
我经常看到 python 代码采用默认参数,并且在未指定参数时具有特殊行为。
例如,如果我想要这样的行为:
def getwrap(dict, key, default = ??):
if ???: # default is specified
return dict.get(key, default)
else:
return dict[key]
如果我自己推出,我最终会得到类似的结果:
class Ham:
__secret = object()
def Cheese(self, key, default = __secret):
if default is self.__secret:
return self.dict.get(key, default)
else:
return self.dict[key]
但当肯定有标准时,我不想发明一些愚蠢的东西。在 Python 中执行此操作的惯用方法是什么?
I often see python code that takes default arguments and has special behaviour when they are not specified.
If I for example want behavior like this:
def getwrap(dict, key, default = ??):
if ???: # default is specified
return dict.get(key, default)
else:
return dict[key]
If I were to roll my own, I'd end up with something like:
class Ham:
__secret = object()
def Cheese(self, key, default = __secret):
if default is self.__secret:
return self.dict.get(key, default)
else:
return self.dict[key]
But I don't want to invent something silly when there certainly is a standard. What is the idiomatic way of doing this in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常更喜欢
,但当然这假设 None 永远不是有效的默认值。
I usually prefer
but of course this assumes that None is never a valid default value.
您可以根据 来做到这一点
*args
和/或**kwargs
。这是基于
*args
的getwrap
的替代实现:下面是它的实际应用:
You could do it based on
*args
and/or**kwargs
.Here's an alternate implementation of
getwrap
based on*args
:And here it is in action: