Lecture 26

Object-oriented Programming 2

Operator overloading

MCS 260 Fall 2021
Emily Dumas


  • Homework 9 available, due Tuesday at 10am
  • Project 3 will be posted this evening
  • Project 3 due 6pm central on Fri Nov 5
  • Review

    Key concepts from Lecture 25

    • class — A type in Python that combines data (attributes) and behavior (methods).
    • instance or object — A value whose type is a certain class (e.g. "hello" is an instance of str)
    • attribute — A variable local to an object, accessed as objname.attrname.
    • constructor — The method named __init__ that is called when a new object is created. Often sets a bunch of attributes using self.attrname = ...

    Goals for today

    Improve our Rectangle and Circle classes.

    Introduce operator overloading.

    Circles and rectangles

    Desired methods

    For both object types:

    • Uniform scale about center
    • Translation by a vector


    When Python needs to convert an object to a string, it calls the __str__(self) method, if it exists.

    Define this and return a string that is a human-readable representation of what the object is.


    How is A==B evaluated when A and B are objects?

    By default, it checks whether the names refer to the same object in memory. This is often not what you want.


    Python allows us to specify our own behavior for operators like ==. This is called operator overloading.

    If method A.__eq__ exists, then A==B evaluates to the return value of A.__eq__(B).


    The built-in function isinstance(obj,cls) returns a bool indicating whether obj is an instance of the class cls, e.g. isinstance(7,int)

    Using it sparingly. Remember, Python recommends EAFP rather that LBYL in most cases.

    EAFP = Easier to Ask Forgiveness than Permission

    LBYL = Look Before You Leap

    Many operators can be overloaded, including:

    ExpressionSpecial method

    List of many more in the Python documentation.

    Overloading built-in functions etc.

    ExpressionActually calls


    Revision history

    • 2021-10-21 Initial publication