两个 python 对象都大于或小于彼此

Two python objects both greater than or less than each other

我正在写一个分数 class,在闲逛时我注意到了这一点:

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


>>> Test()>Test()
True
>>> Test()>Test()
False

这是为什么?

简单地说,你的比较不是直接在class的数据上,而是class本身的实例(id(Foo(1))),因为你没有写这是明确的比较。

它比较实例的id,因此有时是True有时是False。

 Foo(1)
=> <__main__.Foo instance at 0x2a5684>
   Foo(1)
=> <__main__.Foo instance at 0x2a571c>
   Foo(1)