同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
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:
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.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏
