Home > OS >  Get Attribute Error while calling a attribute of specific class in another class in python
Get Attribute Error while calling a attribute of specific class in another class in python

Time:01-05

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

CodePudding user response:

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.

  •  Tags:  
  • Related