Implementation of a comparison of the 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 to implement a comparison against integers, so there's a TypeError exception. However, consider the following two examples:

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

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset