Lecture 26

Object-oriented Programming 2

Operator overloading

MCS 260 Fall 2021
Emily Dumas

Reminders

  • 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

    __str__

    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.

    Equality

    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.

    Overloading

    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).

    isinstance

    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
    A+BA.__add__(B)
    A-BA.__sub__(B)
    A*BA.__mul__(B)
    A/BA.__truediv__(B)
    A**BA.__pow__(B)

    List of many more in the Python documentation.

    Overloading built-in functions etc.

    ExpressionActually calls
    len(A)A.__len__()
    bool(A)A.__bool__()
    A[k]A.__getitem__(k)
    A[k]=vA.__setitem__(k,v)

    References

    Revision history

    • 2021-10-21 Initial publication