加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 指定存在/不存在的默认参数的惯用方法

发布时间:2020-12-20 11:17:04 所属栏目:Python 来源:网络整理
导读:我经常看到 python代码采用默认参数,并且在未指定时具有特殊行为. 如果我想要这样的行为: def getwrap(dict,key,default = ??): if ???: # default is specified return dict.get(key,default) else: return dict[key] 如果我要自己动手,我最终会得到类似的
我经常看到 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,default = __secret):
        if default is self.__secret:
            return self.dict.get(key,default)
        else:
            return self.dict[key]

但是当我确实有一个标准时,我不想发明一些愚蠢的东西.在Python中这样做的惯用方法是什么?

解决方法

我通常更喜欢

def getwrap(my_dict,my_key,default=None):
    if default is None:
        return my_dict[my_key]
    else:
        return my_dict.get(my_key,default)

但当然这假设None永远不是有效的默认值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读