Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active July 18, 2017 02:47
Show Gist options
  • Save allenyang79/f6bc477774040253c5a467ea3083d985 to your computer and use it in GitHub Desktop.
Save allenyang79/f6bc477774040253c5a467ea3083d985 to your computer and use it in GitHub Desktop.
id, hash compare

id 可以取得物件或值的memory address

hash 可透過物件本身的__hash__產生hash代碼,__equal__會用__hash__的結果來檢查兩個物件是否相等

collections.namedtuple本身亦會實作__hash__,因為相同值的namedtuple物件,可以用==來比較是否等價

過大的整數,其id為動態的,看起來應該只是暫時性的

print(id(10 ** 10))
print(id(10 ** 10))
>>>140500617148664
>>>140500617148640
import collections
print(id(10 ** 10))
print(id(10 ** 10))
print(id(10 + 0))
print(id(10))
print "================="
print(id('hello'))
print(id('hello'))
#d = {}
Point = collections.namedtuple("Point", ["x", "y"])
p1 = Point(x=1, y=2)
p2 = Point(x=1, y=2)
print hash(p1)
print hash(p2)
print hash(p1) == hash(p2)
print p1 == p2
print p1 is p2
print id(p1) == id(p2)
print id(p1)
print id(p2)
print "================="
class Foo(object):
def __init__(self, x):
self.data = {'x': x}
f1 = Foo('a')
f2 = Foo('a')
print f1
print f2
print f1 == f2
print hash(f1)
print hash(f2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment