python custom class operator overloading
class, oop, operator-overloading, python
Solution
You have to define the `__eq__` method, as shown below:
class Cat:
def __init__(self, name = "default", age = 0):
self.name = name
self.age = age
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
elif isinstance(other, Cat):
return self.name == other.name
So that when you run your check:
l = [Cat('Joe')]
'Joe' in l
#True
Problem
suppose I have a class: ``` class Cat: def __init__(self, name = "default", age = 0): self.name = name self.age = age ``` I also have a list of Cats: ``` l = [Cat('Joe')] ``` Now I can't call the following: ``` if 'Joe' in l: # the right syntax would be if Cat('Joe') in list ``` Which operator do I need to overload to be able to `identify` objects of class Cat `by` their member variable `name`?