Lecture 24

Object-oriented Programming 2

Operator overloading

MCS 260 Fall 2020
Emily Dumas

Reminders

  • Start on Project 3 immediately. Do not delay!
  • Worksheet 9 available
  • Assignment with operation

    It is common to write assignments that apply one operation to an existing variable and assign the result to that variable.

    Example:

    
            x = x + 25
        

    There is a shorter syntax for this:

    
            x += 25
        

    Not repeating the name x twice can help avoid errors.

    Old wayNew way
    a = a + ba += b
    a = a - ba -= b
    a = a * ba *= b
    a = a / ba /= b
    a = a ** ba **= b
    a = a % ba %= b
    a = a // ba //= b

    Review

    Key concepts from Lecture 23

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

    Goals for today

    Improve our Rectangle and Circle classes.

    Put them in a module.

    Introduce operator overloading.

    Result: geom.py
    (Also see the updated geom.py developed in subsequent lectures.)

    Circles and rectangles

    Desired methods

    For both object types:

    • Uniform scale about center
    • Translation by a vector
    • __str__

    __repr__

    The __repr__ method converts an object to a string that should represent it perfectly; i.e. the object can be completely recovered from the data in the string.

    Contrast to __str__, which emphasizes human readability (maybe at cost of ambiguity).

    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,cl) returns a bool indicating whether obj is an instance of the class cl.

    Using it sparingly. Often it is better to attempt to use expected behavior or attributes, and let an exception detect any problem.

    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

    • 2020-10-21 Change geom.py link to always go to Lecture 24 version
    • 2020-10-17 Initial publication