Home > Blockchain >  Compare object of different class
Compare object of different class

Time:10-12

i'm still pretty new to python and oop, i have the solution for my problem but it's not really performant and i think i miss something.

My code :

class User1:
    
    def __init__(self, foo):
        self.foo = foo

class User2:
    
    def __init__(self, foo):
        self.foo = foo

list_of_user1 = getUser1()
list_of_user2 = getUser2()

def do_something_to_user1():

    do_something_to_user = []  

    for user in list_of_user1:
        if user.foo not in [user.foo for user in list_of_user2]:
            do_something_to_user.append(user)
    for user in do_something_to_user:
        something(user)

def do_something_to_user2():

    do_something_to_user = []  

    for user in list_of_user2:
        if user.foo not in [user.foo for user in list_of_user1]:
            do_something_to_user.append(user)
    for user in do_something_to_user:
        something_else(user)

My question is, how should i compare two object of different class for multiple instance of these class . Is there a better way to do this ?

CodePudding user response:

Following on the comment, the usual OOP way of doing things is by creating a single class User that you instantiate multiple times;

class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

user1 = User("Bob", 20)
user2 = User("Alice", 21)

To compare these two instances, you can implement the __eq__ method.

class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age


user1 = User("Bob", 20)
user2 = User("Alice", 21)
user3 = User("Bob", 20)

print(user1 == user2) # False
print(user1 == user3) # True

In some cases in OOP you might have different types of users. When this occur, this is usually where inheritance is used;

class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age


class Student(User):
    def __init__(self, name: str, age: int, student_id: int):
        super().__init__(name, age)
        self.student_id = student_id

    def __eq__(self, other):
        return super().__eq__(other) and self.student_id == other.student_id


class Teacher(User):
    def __init__(self, name: str, age: int, teacher_id: int):
        super().__init__(name, age)
        self.teacher_id = teacher_id

    def __eq__(self, other):
        return super().__eq__(other) and self.teacher_id == other.teacher_id

I advice looking further into super(), but in short, it calls the parents class method. Hopefully this helps you understand the relationship structure that OOP enforces a little bit better.

  • Related