5

I am writing a Fractions class and while messing around I noticed this:

>>> class Test: def __init__(self): pass >>> Test()>Test() True >>> Test()>Test() False 

Why is this?

10
  • 1
    Can you show us what your function...or rather the class looks like? Commented Feb 10, 2015 at 3:06
  • Your Fraction implementation would be good to see, or the relevant parts with the overloads. Commented Feb 10, 2015 at 3:06
  • What about your __init__ method? Try to show us the complete minimal code. Commented Feb 10, 2015 at 3:08
  • What probably happens is that you either have the comparable mixin, or it just compares the strings from repr. Commented Feb 10, 2015 at 3:10
  • 1
    I've noticed that the same behavior is for this simple case as well: pastebin.com/EX7vpvm9. It only works like this in 2.7. In 3.4 it wont compile even. Commented Feb 10, 2015 at 3:31

1 Answer 1

3

Put simply, your comparisons aren't directly on the data of the class, but the instance of class itself (id(Foo(1))), because you have not written it's comparisons explicitly.

It compares the id of the instances, thus sometimes it's True and other times it's False.

 Foo(1) => <__main__.Foo instance at 0x2a5684> Foo(1) => <__main__.Foo instance at 0x2a571c> Foo(1) 
Sign up to request clarification or add additional context in comments.

7 Comments

Could you explain more. I dont understand why if I run Foo(5) > Foo(2) it will give False, and then when I run the same test again Foo(5) > Foo(2) it will give True?
Your a<b was correct except for the fact that it returned false every time instead of true. Also my question was why, not what could fix it.
I know but that the id is different, but why is the comparison different each time?
When you do Foo(1), this instantiate a class of Foo, thus it can vary every time. However, if you do a = Foo(1), and use a to compare with b in the same manner, you will always get the same result, b/c nothing has been changed, and you are referring to the same variable with same id
It seems like you're right, but I can't find anything in the python reference to support this. The closest I see is a note sying Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program. here but that calls out built-ins specifically and is in the python3 docs too (and this doesn't work in python3)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.