572
edits
Changes
m
→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. However, there is also a way to invoke it by using a special function which ties to the '+' arithmetic operator.
: The '+' operator is 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 the time object.
: Changing or specifying the behaviour of an operator so that it works with programmer-defined types is called '''operator overloading'''.
::* '''Associate the code to the __add__ method''':<source lang="python">
def __add__(self, t2):
"""return self.the result by using sum_times(t2)method"""
</source>
:1. Copy lab7e.py to a new file called lab7f.py. Add the function definition for __add__() after the __str____repr__() function to lab7f.py. Make sure that the '''def __add__(self, t2):''' line has the same indentation level as the __init__() function.
:2. Save the file lab7f.py and test it in an interactive Python shell:<source lang="bash">
[rchan@centos7 lab7]$ python3