Angelo
Angelo

Reputation: 97

How to compare a class return with a float or integer?

I want to compare the __repr__ of a class with a float or an integer.

class TestClass:   
    def __init__(self, a = 5): 
        self.a = a     
    def __repr__(self):
        return self.a

This obviously returns an error, because a is not a string:

TypeError: __repr__ returned non-string (type int)

If I set it as a string, the print is correct:

>>> TestClass()
5

but the print is not comparable:

>>> TestClass() == 5
False

What should I use to compare the class return to make it TestClass() == 5 to True?

Upvotes: 1

Views: 171

Answers (1)

gmds
gmds

Reputation: 19885

Neither.

__repr__ is only called in cases where you need a string and get an object, such as from print or as a single expression on the command line, and is meant as a human-readable representation of an object that it (hopefully) can be reconstructed from.

Recall that without overloading __repr__, what you get from the command line is a string denoting the identity, as opposed to the value, of an object, e.g.:

<__main__.TestClass at 0x20feb8836d8>

On the other hand, what you are doing with TestClass() == 5 is a value comparison.

Therefore, it would only evaluate to True if you defined __eq__, the equality method:

class TestClass:   
    def __init__(self, a = 5): 
        self.a = a    

    def __eq__(self, other):
        return self.a == other

print(TestClass() == 5)

Output:

True

Upvotes: 5

Related Questions