Issue
In Python 3, I have a list (my_array
) that contains an instance of the Demo
class with a certain attribute set on that instance. In my case, the attribute is value: int = 4
.
Given an instance of the Demo
class, how can I determine if that instance already exists in my_array
with the same properties. Here's a MCRE of my issue:
from typing import List
class Demo:
def __init__(self, value: int):
self.value = value
my_array: List[Demo] = [Demo(4)]
print(Demo(4) in my_array) # prints False
However, Demo(4)
clearly already exists in the list, despite that it prints False
.
I looked through the Similar Questions, but they were unrelated.
How can I check if that already exists in the list?
Solution
You need to add an equality function to Demo
:
def __eq__(self, other):
return isinstance(other, Demo) and self.value == other.value
P.S, since Python 3.9 you don't need to import List
and just use:
my_array: list[Demo] = [Demo(4)]
Answered By - Adam.Er8
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.