'Compare object instances of different classes for equality by their attributes
I have two classes:
class A:
def __init__(self, name, id=None, created_at=None):
self.name = name
self.id = id
self.created_at = created_at
def __str__(self):
return f"{self.id} {self.name} {self.created_at}"
def __repr__(self):
return f"{self.id} {self.name} {self.created_at}"
def __eq__(self, other):
if (isinstance(other, A)):
return self.id == other.a_id
And
class B:
def __init__(self, id, a_id, created_at=None):
self.id = id
self.a_id = a_id
self.created_at = created_at
def __str__(self):
return f"{self.id} {self.name} {self.created_at}"
def __repr__(self):
return f"{self.id} {self.name} {self.created_at}"
def __eq__(self, other):
if (isinstance(other, B)):
return self.a_id == other.id
My goal is to get a == b is true if a.id == b.a_id . Like comparing a primary key of a with a foreign key of b. I know eq is not working because I want to compare two different classes. Is there a way to do this in python 3?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
