【发布时间】:2017-09-14 22:36:25
【问题描述】:
这与 python 2.x 相关
在下面的类中,如果我们将“object”子类化,我知道这些方法是在派生类 Foo 中继承的,其中包括__hash__(可以通过打印目录(Foo())
因此调用 hash(Foo()) 调用魔术方法 __hash__ 并给我们一个哈希值。
但是,如果我们不继承“object”,导致 dir(Foo()) 没有列出 __hash__ 方法,那为什么要我们仍然在 python2 中得到一个哈希值?
我相信在 python3 中这个问题已经得到解决,因为来自 "object*" 类的方法是默认继承的。
#class Foo(object) Works since __hash__ is available in the base class
class Foo: #Why does this work?
def __init__(self):
self.x = None
a = Foo()
print dir(a) # No __hash__ magic method
print hash(a)
# Expecting an error like non-hashable or __hash__ not implemented
# or something similar
【问题讨论】:
-
提示:
id(a)仍然有效。相关:stackoverflow.com/questions/17192418/hash-function-in-python
标签: python python-2.7 oop hash python-2.x