Operator Overloading in Classes
We introduced operator overloading at the start of this chapter; let’s fill in a few blanks here and look at a handful of commonly used overloading methods. Here’s a review of the key ideas behind overloading:
Operator overloading lets classes intercept normal Python operations.
Classes can overload all Python expression operators.
Classes can also overload object operations: printing, calls, qualification, etc.
Overloading makes class instances act more like built-in types.
Overloading is implemented by providing specially named class methods.
Here’s a simple example of overloading at work. When we provide
specially named methods in a class, Python automatically calls them
when instances of the class appear in the associated operation. For
instance, the Number
class below provides a method
to intercept instance construction (
__init
__
), as well as one for catching
subtraction expressions (
__ sub
__
). Special methods are the hook that
lets you tie into built-in operations:
class Number: def __init__(self, start): # on Number(start) self.data = start def __sub__(self, other): # on instance - other return Number(self.data - other) # result is a new instance >>>from number import Number
# fetch class from module >>>X = Number(5)
# calls Number.__init__(X, 5) >>>Y = X - 2
# calls Number.__sub__(X, 2) >>>Y.data
3
Common Operator Overloading Methods
Just about everything you can do to built-in objects such as integers and lists has a corresponding specially ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.