1

I have two class: Class1, Class2. assume Class1 is auto-generated and we don't change it. I know input of Class2 is always Class1. I want to compare two object of Class2 but i get an error that attribute "a" Class1 couldn't call in Class2.

This is my code:

class Class1:
    def __init__(self,a ,b) -> None:
        self.a = a
        self.b = b


class Class2:
    def __init__(self, myobject) -> None:
        self.myobject = myobject

    def __eq__(self, other: object) -> bool:
        return self.myobject.a == other.a

    def __str__(self) -> str:
        return str(self.myobject)

variable1=Class2(Class1(1,2))
variable2=Class2(Class1(1,3))

print(variable1==variable2)

The error that i get:

AttributeError: 'Class2' object has no attribute 'a'

Thanks

1 Answer 1

1

You have to compare the inner class of both objects:

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Class2):
            return False
        return self.myobject.a == other.myobject.a

Although I strongly suggest you to improve your variable names to something more descriptive. I also added a type check for robustness.

Sign up to request clarification or add additional context in comments.

1 Comment

:) variable names only for test. Thank you for your suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.