python OrderedDefaultDict 的实现

class OrderedDefaultDict(collections.OrderedDict):
    def __init__(self, *args, **kwargs):
        if not args:
            self.default_factory = None
        else:
            if not (args[0] is None or callable(args[0])):
                raise TypeError('first argument must be callable or None')
            self.default_factory = args[0]
            args = args[1:]
        super(OrderedDefaultDict, self).__init__(*args, **kwargs)

    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        self[key] = default = self.default_factory()
        return default

    def __reduce__(self):
        args = (self.default_factory,) if self.default_factory else ()
        return self.__class__, args, None, None, self.iteritems()

__missing__():

missing 主要是defaultdict类中实现默认值的功能,
使用

print defaultdict.__missing__.__doc__

missing(key)
if self.default_factory is None: raise KeyError(key)
self[key] = value = self.default_factory()
return value

通过查看_ _ missing _ ()方法的docstring, 可以看出,当使用 _ getitem _ 方法访问一个不存在的键的时候,会调用 _ missing _ _ 方法来获取默认值,并将该值添加到字典中去

而且查看官方文档发现,

If a subclass of dict defines a method missing() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the missing(key) call. No other operations or methods invoke missing(). If missing() is not defined, KeyError is raised. missing() must be a method; it cannot be an instance variable:

虽然dict支持 miss 方法,但是该方法在dict本身是不存在的,而是需要在派生的子类中自行实现这个方法,可以简单的验证这一点:

print dict.__missing__.__doc__

同时,我们可以进一步的做实验,定义一个子类,并且实现 missing方法

class Missing(dict)
    def __missing__(self, key):
        return 'missing'

d = Missing()
>>>d
{}
>>>d['foo']
'missing'
>>>d
{}

返回结果反映了,missing方法确实发挥了作用,在此基础上,我们稍作修改就可以使得该子类同defaultdict类一样为不存在的键设置一个默认值

__reduce__self

当定义扩展类型的时候(也就是使用python的C语言API实现的类型), 如果你想要pickle(持久化对象)它们,你必须告诉python如何pickle它们,reduce被定义之后,当对象被pickle的时候就会被调用,它要么返回一个代表全局名称的字符串,python会查找它并且pickle,要么返回一个元组,这个元组包含2到5个元素,其中包括:一个可调用对象,用于重建对象的时候调用,一个参数元素,供那个可调用对象使用,被传递给 _ _ setstate _ _ 的状态(可选); 一个产生被pickle的列表元素的迭代器(可选) 一个产生pickle的字典元素的迭代器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值