Skip to content

Instantly share code, notes, and snippets.

@tuxcanfly
Created July 25, 2012 06:11
Show Gist options
  • Save tuxcanfly/3174684 to your computer and use it in GitHub Desktop.
Save tuxcanfly/3174684 to your computer and use it in GitHub Desktop.
Sets and Hash
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 (?)
@akshar-raaj
Copy link

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>])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment