Reputation: 10996
I have a custom class which I want to be able to use as a key in a dictionary. So, I need to define the __eq__
function. In my case, this is simple:
def __eq__(self, other):
return self.name == other.name
Here other
needs to be basically of the same type and I am comparing some member variables. However, the name
is just a string and what I was thinking was that the user could also check by specifying a string. To make it concrete, here is what I had in mind:
class Hashable(object):
def __init__(self, name):
self.name = name
self.other_att = dict()
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
# Example usage
from collections import defaultdict
c = defaultdict()
h = Hashable("Name")
c[h] = list()
if h in c:
print ("Yes!") # This is fine...
However, also want to do:
if 'Name' in c:
Can I implement many __eq__
functions or do I need to check for the type of other
in the equality function. What is a pythonic an hopefully efficient way to do this?
Upvotes: 0
Views: 120
Reputation: 107297
You can just use a try-except
, because sometimes it's easier to ask for forgiveness than permission:
def __eq__(self, other):
try:
return self.name == other.name
except AttributeError:
return self.name == other
Upvotes: 2
Reputation: 78554
Use getattr
and provide the default as other
in case other
has no attribute name
e.g. it's a string:
def __eq__(self, other):
return self.name == getattr(other, 'name', other)
Upvotes: 2