Book Image

Mastering Object-oriented Python

By : Steven F. Lott, Steven F. Lott
Book Image

Mastering Object-oriented Python

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
Index

The comparison operator methods


Python has six comparison operators. These operators have special method implementations. According to the documentation, the mapping works as follows:

  • x<y calls x.__lt__(y)

  • x<=y calls x.__le__(y)

  • x==y calls x.__eq__(y)

  • x!=y calls x.__ne__(y)

  • x>y calls x.__gt__(y)

  • x>=y calls x.__ge__(y)

We'll return to comparison operators again when looking at numbers in Chapter 7, Creating Numbers.

There's an additional rule regarding what operators are actually implemented that's relevant here. These rules are based on the idea that the object's class on the left defines the required special method. If it doesn't, Python can try an alternative operation by changing the order.

Tip

Here are the two basic rules

First, the operand on the left is checked for an operator implementation: A<B means A.__lt__(B).

Second, the operand on the right is checked for a reversed operator implementation: A<B means B.__gt__(A).

The rare exception to this occurs when the...