Changes

Jump to: navigation, search

Rchan sandbox

2,318 bytes added, 19:54, 3 November 2019
Part 3 - Operator overloading
== Part 3 - Operator overloading ==
: Attached code 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. How, there is any way to invoke it by using a special function which ties to the '+' arithmetic operator .: The '+' and operator is bind 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 support tell the python interpreter to perform sum operation on thw time object.: Changing or specifying the behaviour of adding 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 object.::* Associate the following code to the __add__ method for Time class in lab7d.py:<source lang="python">
def __add__(self, t2):
seconds = return self.time_to_secsum_times() + t2.time_to_sec() return sec_to_time(seconds)
</source>
:1. Add the function definition for __add__() after the __str__() function in lab7d.py. Make sure that the '''def __add__(self, t2):''' line has the same indentation level as the __init__() function.
:2. Save the file lab7d.py and test it in an interactive Python shell:<source lang="bash">
[rchan@centos7 lab7]$ python3
Python 3.4.9 (default, Aug 14 2018, 21:28:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lab7d import *
>>> t1 = Time(9,50,0)
>>> t2 = Time(1,1,1)
>>> t1.sum_times(t2)
10.51.01
>>> t2.sum_times(t1)
10.51.01
>>> t1 + t2
10.51.01
>>> x = t1 + t2
>>> type(x)
<class 'lab7d.Time'>
>>> print(x)
10:51:01
</source>
::* Note: If you get different results, please troubleshoot your lab7d.py file and fix any discrepancy.
:3. Download the checking script and check your work. Enter the following commands from the bash shell.<source lang="bash">
cd ~/ops435/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab7.py
python3 ./CheckLab7.py -f -v lab7d
</source>
:4. Before proceeding, make certain that you identify all errors in lab7a.py. When the checking script tells you everything is OK - proceed to the next step.
= Investigation III - Objects and Scope =
1,760
edits

Navigation menu