Skip to content

Instantly share code, notes, and snippets.

@glesica
Created March 11, 2015 19:53
Show Gist options
  • Save glesica/9ddacb0ae0560a2d47be to your computer and use it in GitHub Desktop.
Save glesica/9ddacb0ae0560a2d47be to your computer and use it in GitHub Desktop.
Brief exploration of Python's magic methods for equality testing.
# Equality in Python
# When using custom types (classes) many programmers like to be able
# to use built-in concepts like "==" instead of something like
# "a.equals(b)". Generally it is only a good idea to do this if the
# concept you are implementing is conceptually the same as what the
# operator is normally used for. An example:
class Person1(object):
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person1('George', 32)
p2 = Person1('George', 32)
print 'Person1 - will print false even though the objects look the same'
print p1 == p2
class Person2(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return (self.name == self.name) and (self.age == other.age)
def __ne__(self, other):
return not (self == other)
p1 = Person2('George', 32)
p2 = Person2('George', 32)
print 'Person2 - now it prints true'
print p1 == p2
# Once we implemented some special (Python calls them "magic")
# methods, Python saw them when we made the comparison and used them
# instead of its default behavior (which is to compare whether they
# are the same object, in other words, the same data in memory). We
# aren't strictly limited to things that a reasonable person would
# call "equal" though (but doing stuff like this is usually a bad idea
# because it is confusing).
class Person3(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return (self.age == other.age)
def __ne__(self, other):
return not (self == other)
p1 = Person3('George', 32)
p2 = Person3('Brian', 32)
print 'Person3 - prints true, which is a little confusing'
print p1 == p2
# Whether to do this is just a judgement call. Sometimes it can be
# slightly confusing but make the code cleaner, which might be
# important. This is where programming is more of an art than a
# science.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment