Created
July 25, 2012 06:11
-
-
Save tuxcanfly/3174684 to your computer and use it in GitHub Desktop.
Sets and Hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User(object): | |
def __init__(self, username=''): | |
self.username = username | |
def __hash__(self): | |
return hash(self.username) | |
foo = User('foobar') | |
bar = User('foobar') | |
assert hash(foo) == hash(bar) #True | |
users = set() | |
users.add(foo) | |
users.add(bar) | |
assert len(users) == 1 # False (?) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In [61]: class User(object):
def init(self, username=''):
self.username = username
def hash(self):
return hash(self.username)
def eq(self, other):
return hash(self.username)==hash(other.username)
....:
....:
In [68]: foo=User('foo')
In [69]: bar = User('foo')
In [70]: foo==bar
Out[70]: True
In [71]: users = set()
In [72]: users
Out[72]: set()
In [73]: users.add(foo)
In [74]: users
Out[74]: set([<main.User object at 0xb1e2f0c>])
In [75]: users.add(bar)
In [76]: users
Out[76]: set([<main.User object at 0xb1e2f0c>])