代码之家  ›  专栏  ›  技术社区  ›  saulspatz

将super与getitem与subscript一起使用

  •  0
  • saulspatz  · 技术社区  · 7 年前

    我在写 dict 只有正整数的元组作为键。如果键是未知的并且元组的元素之一是 1 ,查找应返回默认值 0 是的。任何其他未知密钥都应引发 KeyError 是的。

    这很管用:

    class zeroDict(dict):
        '''
        If key not in dict and an element of the tuple is 
        a 1, impute the value 0.
        '''    
        def __init__self():
            super().__init__()
        def __getitem__(self, key):
            try:
                return super().__getitem__(key)
            except KeyError:
                if 1 in key:
                    return 0
                else:
                    raise   
    

    这不会:

    class zDict(dict):
        '''
        If key not in dict and an element of the tuple is 
        a 1, impute the value 0.
        '''    
        def __init__self():
            super().__init__()
        def __getitem__(self, key):
            try:
                return super()[key]
            except KeyError:
                if 1 in key:
                    return 0
                else:
                    raise  
    

    当我试图从 zDict 我明白了 TypeError: 'super' object is not subscriptable 是的。

    实现之间的唯一区别是 zeroDict

    return super().__getitem__(key) 
    

    ZDICT公司

    return super()[key]
    

    然而, help(dict.__getitem__) 印刷品

    __getitem__(...)
        x.__getitem__(y) <==> x[y]   
    

    这似乎说明这两种说法是等价的。这是怎么回事?

    0 回复  |  直到 7 年前
        1
  •  0
  •   juanpa.arrivillaga    7 年前

    正如其他人所解释的那样, super() 在这里不工作是因为它返回一个 超级对象 ,它是一个代理对象,处理按方法解析顺序将点式属性访问分派给下一个类。

    尽管如此,你不应该凌驾于 __getitem__ 在这里,python数据模型提供了一些 就为了这个案子 ,它是 __missing__ method :

    object.__missing__(self, key)

    实施 self[key] 当键不在 字典。由调用 dict.__getitem__()

    所以,这样做:

    class ZeroDict(dict):
        def __missing__(self, key):
            if 0 in key:
                return 0
            else:
                raise KeyError(key)
    

    还有一个演示:

    >>> class ZeroDict(dict):
    ...     def __missing__(self, key):
    ...         if 0 in key:
    ...             return 0
    ...         else:
    ...             raise KeyError(key)
    ...
    >>> d = ZeroDict()
    >>> d[(1, 0)] = 'foo'
    >>> d
    {(1, 0): 'foo'}
    >>> d[1, 0]
    'foo'
    >>> d[1, 1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in __missing__
    KeyError: (1, 1)
    >>> d[0, 1]
    0
    >>>