I would like to compare list which contain some class using implicator in. Code below:
class Word: def __init__(self, p_name): self.name = p_name def __eq__(self, other): return self.name == other.name def __str__(self): return "_name_: " + self.name t1 =  t1.append(Word("John")) t2 =  t2.append(Word("John")) if t1 in t2: print("the same")
I got an error that "list has no attribute 'name'". I know that I can write some loops but I would like to use implicator in if it is possible in such situation.
if t1 in t2:
Should be one of these:
# Check if a single word is in t2.
w = Word("John")
if w in t2:
# Check if any element of t1 is in t2.
if any(w in t2 for w in t1):
# Check if all elements of t1 are in t2.
if all(w in t2 for w in t1):
You should not be checking if one list is in another list. You either want to check if a particular item is in a list, or you want to compare all of the items in
t1 with the items in
def __eq__(self, other):
return isinstance(other, Word) and self.name == other.name
It would also be a good idea to add a check to
other is a
Word. Your code blows up because
other is a list not a
Word, and so the
other.name lookup fails.