代码之家  ›  专栏  ›  技术社区  ›  Don O'Donnell

与python 3.1文档相反,hash(obj)!= ID(OBJ)。那么哪个是正确的呢?

  •  10
  • Don O'Donnell  · 技术社区  · 15 年前

    下面是来自python v3.1.2文档的内容:

    从python语言参考第3.3.1节基本定制:

    object.__hash__(self)
    
    ... User-defined classes have __eq__() and __hash__() methods 
    by default; with them, all objects compare unequal (except
    with themselves) and x.__hash__() returns id(x).
    

    从术语表:

    hashable
    
    ... Objects which are instances of user-defined classes are 
    hashable by default; they all compare unequal, and their hash 
    value is their id().
    

    这是通过版本2.6.5实现的:

    Python 2.6.5 (r265:79096, Mar 19 2010 21:48:26) ...
    ...
    >>> class C(object): pass
    ...
    >>> c = C()
    >>> id(c)
    11335856
    >>> hash(c)
    11335856
    

    但在3.1.2版中:

    Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ...
    ...
    >>> class C: pass
    ...
    >>> c = C()
    >>> id(c)
    11893680
    >>> hash(c)
    743355
    

    那是哪一个呢?我应该报告文档错误还是程序错误? 如果是文档错误,那么 hash() 用户的值 类实例不再与 id() 价值,那就是 有意思的是知道它是什么或者它是如何计算的,以及它为什么是 在版本3中更改。

    1 回复  |  直到 15 年前
        1
  •  10
  •   ʇsәɹoɈ    15 年前

    我猜这是为了提高性能而在python 3.x中做的一个更改。退房 issue 5186 ,然后更仔细地观察您不匹配的数字:

    >>> bin(11893680)
    '0b101101010111101110110000'
    >>> bin(743355)
    '0b10110101011110111011'
    >>> 11893680 >> 4
    743355
    

    它可能值得作为文档缺陷进行报告。