Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

Implementation of comparison for objects of mixed classes

We'll use the BlackJackCard class as an example to see what happens when we attempt comparisons where the two operands are from different classes.

The following is a Card instance that we can compare against the int values:

>>> two = card21( 2, '♣' )
>>> two < 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: Number21Card() < int()
>>> two > 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: Number21Card() > int()

This is what we expected: the subclass of BlackJackCard, Number21Card doesn't provide the required special methods, so there's a TypeError exception.

However, consider the following two examples:

>>> two == 2
False
>>> two == 3
False

Why do these provide responses? When confronted with a NotImplemented value, Python will reverse the operands. In this case, the integer values define an int.__eq__() method that tolerates objects of an unexpected class.