Changes

Jump to: navigation, search

OPS435 Python3 Lab 7

9 bytes added, 23:19, 12 March 2020
Part 3 - Operator overloading
== Part 3 - Operator overloading ==
: Remember we define the sum_times() function to add to time objects and return their sum? After we moved the function definition under the class definition in lab7d.py, it became a class function, and method for the time object. It can be invoked by using the Time.sum_times(t1,t2) syntax or t1.sum_times(t2) syntax. HowHowever, there is any also a way to invoke it by using a special function which ties to the '+' arithmetic operator.: The '+' operator is bind bound to the special function of an object's __add__() method. If we attached the same code we have for the sum_times() function to the special function __add__() for the time object, the we can use the '+' operator to tell the python interpreter to perform sum operation on thw the time object.
: Changing or specifying the behaviour of an operator so that it works with programmer-defined types is called '''operator overloading'''.
: Let's add the appropriate code to the __add__ function to overload the '+' operator so that we can use an arithmetic expression to tell the python interpreter to add two time objectobjects.
::* '''Associate the code to the __add__ method''':<source lang="python">
def __add__(self, t2):
14
edits

Navigation menu