预计阅读本页时间:-
Comparisons: __lt__, __gt__, and Others
As suggested in Table 29-1, classes can define methods to catch all six comparison operators: <, >, <=, >=, ==, and !=. These methods are generally straightforward to use, but keep the following qualifications in mind:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- Unlike the __add__/__radd__ pairings discussed earlier, there are no right-side variants of comparison methods. Instead, reflective methods are used when only one operand supports comparison (e.g., __lt__ and __gt__ are each other’s reflection).
- There are no implicit relationships among the comparison operators. The truth of == does not imply that != is false, for example, so both __eq__ and __ne__ should be defined to ensure that both operators behave correctly.
- In Python 2.6, a __cmp__ method is used by all comparisons if no more specific comparison methods are defined; it returns a number that is less than, equal to, or greater than zero, to signal less than, equal, and greater than results for the comparison of its two arguments (self and another operand). This method often uses the cmp(x, y) built-in to compute its result. Both the __cmp__ method and the cmp built-in function are removed in Python 3.0: use the more specific methods instead.
We don’t have space for an in-depth exploration of comparison methods, but as a quick introduction, consider the following class and test code:
class C:
data = 'spam'
def __gt__(self, other): # 3.0 and 2.6 version
return self.data > other
def __lt__(self, other):
return self.data < other
X = C()
print(X > 'ham') # True (runs __gt__)
print(X < 'ham') # False (runs __lt__)
When run under Python 3.0 or 2.6, the prints at the end display the expected results noted in their comments, because the class’s methods intercept and implement comparison expressions.