0

In Python, if I have the following code:

r = Numeric(str)
i = int(r)
if r == i :
    return i
return r

Is this equivalent to:

r = Numeric(str)
return r

Or do the == values of different types r and i give different return values r and i?

3 Answers 3

4

It all depends if the class implements an adequate __eq__ method to override == operator.

Edit: Added a little example:

>>> class foo:
...     def __init__(self,x):
...         self.x = x
...     def __eq__(self,y):
...         return int(self.x)==int(y)
... 
>>> f = foo(5)
>>> f == '5'
True
>>> 5 == '5'
False
Sign up to request clarification or add additional context in comments.

Comments

2

Lets see:

>>> float(2) == int(2)
True

Different types can be considered equal using ==.

Comments

1

Question: "do the == values of different types r and i give different return values r and i?"

Answer: clearly they are different; they have different types.

>>> print(type(i))
<type 'int'>
>>> print(type(n))
<class '__main__.Numeric'>

In the above example, I declared a class called Numeric to have something to test. If you actually have a module that implements a class called Numeric, it won't say __main__.Numeric but something else.

If the class implements a __eq__() method function, then the results of == will depend on what that function does.

class AlwaysEqual(object):
    def __init__(self, x):
        self.x = x
    def __eq__(self, other):
        return True

With the above, we can now do:

>>> x = AlwaysEqual(42)
>>> print(x == 6*9)
True
>>> print(x == "The answer to life, the universe, and everything")
True

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.