Skip to main content
Engineering LibreTexts

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}\)
    Learning Objectives

    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.

    Checkpoint: Customizing __str__() in a user-defined class, Engineer
    Concepts in Practice \(\PageIndex{1}\): Magic methods

    Which of the following is a magic method?

    1. add()
    2. _add_()
    3. __add__()
    Answer

    c. __add__() is a magic method, indicated by the double underscores at the start and end of the method name.

    Concepts in Practice \(\PageIndex{2}\): Magic methods

    Why are magic methods special?

    1. can't be called by the user
    2. perform internal actions
    3. 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.

    Concepts in Practice \(\PageIndex{3}\): Magic methods

    Consider the example above, and identify the magic method(s) in the updated program.

    1. __init__()
    2. __str__()
    3. __init__(), __str__()
    Answer

    c. __init__() is defined by the programmer to initialize instance attributes. __str__() is defined by the programmer to customize an Engineer instance'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.

    Checkpoint: Overloading __add__() for a user-defined class, Account
    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)
    Table 11.1: Arithmetic operators and magic methods.
    Concepts in Practice \(\PageIndex{4}\): Arithmetic operator overloading

    A programmer explicitly defining the modulo operator for their user-defined class is ___________ the operator.

    1. overloading
    2. rewriting
    3. implementing
    Answer

    a. A programmer can overload an operator to customize the built-in operator's function.

    Concepts in Practice \(\PageIndex{5}\): Arithmetic operator overloading

    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
    
    1. acct_a
    2. acct_b
    3. acct_ab
    Answer

    b. The addition operation maps the left operand, acct_a, to the parameter self and the right operand, acct_b, to the parameter other.

    Concepts in Practice \(\PageIndex{6}\): Arithmetic operator overloading

    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)
    
    1.   def __sub__(self):
          return Pair(self.x - other.x, self.y - other.y)
      
    2.   def __sub__(self, other):
          return self.x - other.x, self.y - other.y
      
    3.   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' x and y attributes are subtracted from each other, and the resulting values are made into a new Pair.

    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)
    Table 11.2: Comparison operators and magic methods.
    Example 11.2: Overloading comparison operators for the Account class
    Table 11.3
    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
    Concepts in Practice: Comparison operator overloading

    Consider the example above.

    Concepts in Practice \(\PageIndex{7}\): Comparison operator overloading

    How many operators are overloaded?

    1. 3
    2. 4
    3. 5
    Answer

    a. <, >, and == are overloaded with __lt__(), __gt__(), and __eq__(), respectively.

    Concepts in Practice \(\PageIndex{8}\): Comparison operator overloading

    Which code appropriately overloads the <= operator?

    1.   def __le__(other):
          return self.amount <= other.amount
      
    2.   def __le__(self, other):
          return self.amount <= other.amount
      
    3.   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.

    Concepts in Practice \(\PageIndex{9}\): Comparison operator overloading

    Which type of value does __gt__() return?

    1. account instance
    2. Boolean
    3. integer
    Answer

    b. __gt__() overloads the > operator, which makes a comparison and returns True or False .

    Try It: Combining exercise logs

    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
    class ExerciseLog:
        def __init__(self, e_type="", duration=0):
            self.e_type = e_type
            self.duration = duration
    
        def __str__(self):
            return f"{self.e_type}: {self.duration} minutes"
    
    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)
     
    Input

    cycle
    45
    run
    15

    Answer

    class ExerciseLog:
    def __init__(self, e_type="", duration=0):
    self.e_type = e_type
    self.duration = duration

    def __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)

    Try It: Expanding the Account class

    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
    class Account:    
        def __init__(self, name="", amount=0): 
            self.name = name
            self.amount = amount    
    
        def __str__(self):
            return f"{self.name}: ${self.amount}"
    
        def __add__(self, other):
            # Add code to allow adding int values too
            return Account(self.name + ", " + other.name,
                           self.amount + other.amount)
    
    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)
     
    Input

    Ashe
    4959
    Bevins
    8374

    Answer

    class Account:
    def __init__(self, name="", amount=0):
    self.name = name
    self.amount = amount

    def __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)


    This page titled 11.4: Overloading Operators is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.