11.4: Overloading Operators
- Page ID
- 117595
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)By the end of this section you should be able to
- Identify magic methods and describe their purpose.
- Develop overloaded arithmetic and comparison operators for user-defined classes.
Magic methods and customizing
Magic methods are special methods that perform actions for users, typically out of view of users. Magic methods are also called dunder methods, since the methods must start and end with double underscores (__). Ex: __init__() is a magic method used alongside __new__() to create a new instance and initialize attributes with a simple line like eng = Engineer(). A programmer can explicitly define a magic method in a user-defined class to customize the method's behavior.
Which of the following is a magic method?
add()_add_()__add__()
- Answer
-
c.
__add__()is a magic method, indicated by the double underscores at the start and end of the method name.
Why are magic methods special?
- can't be called by the user
- perform internal actions
- have fixed definitions
- Answer
-
b. Magic methods are designed to be invoked internally to perform under-the-hood actions to simplify tasks for the user.
Consider the example above, and identify the magic method(s) in the updated program.
__init__()__str__()__init__(),__str__()
- Answer
-
c.
__init__()is defined by the programmer to initialize instance attributes.__str__()is defined by the programmer to customize anEngineerinstance's string representation.
Overloading arithmetic operators
Operator overloading refers to customizing the function of a built-in operator. Arithmetic operators are commonly overloaded to allow for easy changes to instances of user-defined classes.
| Arithmetic operator (Operation) | Magic method |
|---|---|
| + (Addition) |
__add__(self, other) |
| - (Subtraction) |
__sub__(self, other) |
| * (Multiplication) |
__mul__(self, other) |
| / (Division) |
__truediv__(self, other) |
| % (Modulo) |
__mod__(self, other) |
| ** (Power) |
__pow__(self, other) |
A programmer explicitly defining the modulo operator for their user-defined class is ___________ the operator.
- overloading
- rewriting
- implementing
- Answer
-
a. A programmer can overload an operator to customize the built-in operator's function.
Given the code below, which argument maps to the parameter other in the call to Account.__add__()?
acct_a = Account("Ashe", 6492)
acct_b = Account("Bevins", 5210)
acct_ab = acct_a + acct_b
acct_aacct_bacct_ab
- Answer
-
b. The addition operation maps the left operand,
acct_a, to the parameterselfand the right operand,acct_b, to the parameterother.
Which __sub__() definition overloads the - operator for the code below to work?
class Pair:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# Define __sub__()
p1 = Pair(10, 2)
p2 = Pair(8, 4)
p3 = p1 - p2
print(p3.x, p3.y)
-
def __sub__(self): return Pair(self.x - other.x, self.y - other.y) -
def __sub__(self, other): return self.x - other.x, self.y - other.y -
def __sub__(self, other): return Pair(self.x - other.x, self.y - other.y)
- Answer
-
c. - is a binary operator, so
__sub__()has two parameters. The parameters'xandyattributes are subtracted from each other, and the resulting values are made into a newPair.
Overloading comparison operators
Comparison operators can also be overloaded like arithmetic operators.
| Comparison operator (Operation) | Magic method |
|---|---|
| < (Less than) |
__lt__(self, other) |
| > (Greater than) |
__gt__(self, other) |
| <= (Less than or equal to) |
__le__(self, other) |
| >= (Greater than or equal to) |
__ge__(self, other) |
| == (Equal) |
__eq__(self, other) |
| != (Not equal) |
__ne__(self, other) |
| Code | Output |
|---|---|
class Account:
def __init__(self, name="", amount=0):
self.name = name
self.amount = amount
def __str__(self):
return f"{self.name}: ${self.amount}"
def __lt__(self, other):
return self.amount < other.amount
def __gt__(self, other):
return self.amount > other.amount
def __eq__(self, other):
return self.amount == other.amount
acct_a = Account("Ashe", 6492)
acct_b = Account("Bevins", 5210)
print(acct_a < acct_b)
print(acct_a > acct_b)
acct_a.amount = 5210
print(acct_a == acct_b)
|
False
True
True
|
Consider the example above.
How many operators are overloaded?
- 3
- 4
- 5
- Answer
-
a. <, >, and == are overloaded with
__lt__(),__gt__(), and__eq__(), respectively.
Which code appropriately overloads the <= operator?
-
def __le__(other): return self.amount <= other.amount -
def __le__(self, other): return self.amount <= other.amount -
def __le__(self, other): return other.amount <= self.amount
- Answer
-
b.
__le__()is the magic method for the <= operator.__le__()takes two parameters for the left and right operand, and returns the correct comparison of the two amount values.
Which type of value does __gt__() return?
- account instance
- Boolean
- integer
- Answer
-
b.
__gt__()overloads the > operator, which makes a comparison and returnsTrueorFalse.
The ExerciseLog class has two instance attributes: e_type, the type of exercise, and duration, the time spent exercising.
Overload the + operator to combine two ExerciseLogs such that:
- If the exercise types are different, combine them with
" and "in between. Else, use the same type and don't duplicate. - Add durations together.
Given input:
walk
5
run
30
The output is:
walk and run: 35 minutes
Interactive Code
- Input
-
cycle
45
run
15 - Answer
-
class ExerciseLog:
def __init__(self, e_type="", duration=0):
self.e_type = e_type
self.duration = durationdef __str__(self):
return f"{self.e_type}: {self.duration} minutes"def __add__(self, other):
if self.e_type != other.e_type:
return ExerciseLog(f"{self.e_type} and {other.e_type}", self.duration + other.duration)
else:
return ExerciseLog(self.e_type, self.duration + other.duration)exercise1 = input()
duration1 = int(input())
log1 = ExerciseLog(exercise1, duration1)
exercise2 = input()
duration2 = int(input())
log2 = ExerciseLog(exercise2, duration2)log_combined = log1 + log2
print(log_combined)
Using isinstance() allows the programmer to define different behaviors depending on an object's type. The first parameter is the object, and the second parameter is the type or class. Ex: isinstance(my_var, int) returns True if my_var is an integer.
Expand the existing Account example so that the addition operator can also be used to add an integer value to an Account's amount attribute.
Interactive Code
- Input
-
Ashe
4959
Bevins
8374 - Answer
-
class Account:
def __init__(self, name="", amount=0):
self.name = name
self.amount = amountdef __str__(self):
return f"{self.name}: ${self.amount}"def __add__(self, other):
if isinstance(other, Account):
return Account(self.name + ", " + other.name,
self.amount + other.amount)
elif isinstance(other, int):
return Account(self.name, self.amount + other)name_a = input()
amt_a = int(input())
acct_a = Account(name_a, amt_a)
name_b = input()
amt_b = int(input())
acct_b = Account(name_b, amt_b)acct_ab = acct_a + acct_b # Combine accounts
print(acct_ab)fund = int(input())
acct_ab = acct_ab + fund
print(acct_ab)


