The 2.6 __cmp__ Method (Removed in 3.0)

In Python 2.6, the __cmp__ method is used as a fallback if more specific methods are not defined: its integer result is used to evaluate the operator being run. The following produces the same result under 2.6, for example, but fails in 3.0 because __cmp__ is no longer used:

class C:
    data = 'spam'                          # 2.6 only
    def __cmp__(self, other):              # __cmp__ not used in 3.0
        return cmp(self.data, other)       # cmp not defined in 3.0

X = C()
print(X > 'ham')                           # True  (runs __cmp__)
print(X < 'ham')                           # False (runs __cmp__)

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Notice that this fails in 3.0 because __cmp__ is no longer special, not because the cmp built-in function is no longer present. If we change the prior class to the following to try to simulate the cmp call, the code still works in 2.6 but fails in 3.0:

class C:
    data = 'spam'
    def __cmp__(self, other):
        return (self.data > other) - (self.data < other)


Note

So why, you might be asking, did I just show you a comparison method that is no longer supported in 3.0? While it would be easier to erase history entirely, this book is designed to support both 2.6 and 3.0 readers. Because __cmp__ may appear in code 2.6 readers must reuse or maintain, it’s fair game in this book. Moreover, __cmp__ was removed more abruptly than the __getslice__ method described earlier, and so may endure longer. If you use 3.0, though, or care about running your code under 3.0 in the future, don’t use __cmp__ anymore: use the more specific comparison methods instead.