Open main menu

CDOT Wiki β

Changes

Rchan sandbox

4,903 bytes added, 21:29, 3 November 2019
LAB 7 SIGN-OFF (SHOW INSTRUCTOR)
:# Create functions to process programmer-defined type objects.
:# Bind functions into methods for programmer-defined type objects.
:# Set the appropriate scope when creating new object: local and global
==Overview==
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
: In the previous investigation, the functions that were defined for manipulating our time object are not tied directly to our time object. Given our time object alone, we won't be able to tell that there exist a function called sum_times() which can be used to add two time objects and return their sum.
:<br>
: To tie up those functions to our time objects, we only need to move those functions definition under the class block which defines our Time object. When we move an external function into a class block, we need to add an extra function parameter and make it the first in the parameter list. By convention, we always name it as '''self'''.
== Part 1 - Classes and Methods for our Time objects ==
: The following illustration shows how we can change external functions to become object methods (aka class functions) for our Time object. It is simply by moving the function definitions to be under the class definition for the Time objectand add 'self' as the first parameter for each function: <source lang="python">
#!/usr/bin/env python3
# Student ID: rchan[seneca_id]
class Time:
"""Simple object type for time of the day.
"""Add two time objests and return the sum."""
sum = Time(0,0,0)
sec1 self_sec = self.time_to_sec(self) sec2 t2_sec = t2.time_to_sec(self)
sum = sec_to_time(sec1 + sec2)
return sum
def change_time(self, seconds):
time_seconds = self.time_to_sec(self)
nt = sec_to_time(time_seconds + seconds)
time.hour, time.minute, time.second = nt.hour, nt.minute, nt.second
return seconds
def valid_time(tself):
"""check for the validity of the time object attributes:
24 > hour > 0, 60 > minute > 0, 60 > second > 0 """
if tself.hour < 0 or tself.minute < 0 or tself.second < 0:
return False
if tself.minute >= 60 or tself.second >= 60 or tself.hour >= 24:
return False
return True
</source>
: Please notice that the function named sec_to_time() did not get moved under the class block. It remains as an external function.
:1. Create a new python file and name it as '''lab7d.py''' and place the code listed above in it.
:2. Save the file, and test the new time object in an interactive Python shell: <source lang="bash">
[rchan@centos7 lab7]$ python3
:3. Please study the output of the interactive shell session above and note that in order to call the format_time() function, we have to prefix it with the class name '''Time''' as it is under the class definition in lab7d.py. Also note that format_time() is now a method of the time object '''t1'''.
:4. You may also notice that when we called the print() function with our time object t1, the print function only showed that it is an Time object and its memory location, but did not display its properties (i.e. data attributes) like the values of its hour, minute, and second attributes.
:5. Try to find out how to test the valid_date(), change_time() functions to make sure they all work.
:6. 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>
:7. Before proceeding, make certain that you identify all errors in lab7d.py. When the checking script tells you everything is OK - proceed to the next step.
== Part 2 - Special object methods ==
: Each programmer-defined object has a few special methods which can be used to manipulate the object, the one we already know is the '''__init__''' method, which python refers it as the object constructor, and we can associate code to this method in the class definition.
: In this part, we are going to investigate and study the '''__str__''' and '''__repr__''' special methods.
::*'''Associate the following code to the __str__''' method for the Time class in lab7d.py: <source lang="python">
def __str__(self):
'''return a string representation for the object self'''
return '%.2d:%2d:%2d' % (self.hour, self.minute, self.second)
</source>
::1. Make a copy of lab7d.py and name it as lab7e.py. Add the function definition for __str__() after the __init__() function in lab7dlab7e.py. Make sure that the '''def __str__(self):''' line has the same indentation level as the __init__() function.::2. Save the file lab7dlab7e.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 lab7d1 lab7e import *
>>> t1 = Time(9,50,0)
>>> t1
<lab7d1lab7e.Time object at 0x7f830b498be0>
>>> print(t1)
09.50.00
>>>
</source>
::3. Now with the proper code (same code for the format_time() function) attached to the __str__ methon, we have a string representation for our time object that the print() function can/will use.::4. You will still notice that typing the time object name itself on an interactive python shell, type the Python interpreter will just display the type of the object and its location in memory. ::5. Let's look at the next special object method '''__repr__()'''. We can also attached code to this function to tell the python interpreter what we want would like the object to appear on look like in an interactive shell.::6. * '''Associate the following code to the __repr__''' method for the Time class in lab7d.py: <source lang="python">
def __repr__(self):
'''return a string representation for the object self'''
return '%.2d.%2d.%2d' % (self.hour, self.minute, self.second)
</source>
:6. Add the function definition for __repr__() after the __str__() function in lab7e.py. Please note that we use the '.' instead of ':' in the formatting string. Make sure that the '''def __repr__(self):''' line has the same indentation level as the __init__() function.
:7. Save the file lab7e.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 lab7e import *
>>> t1 = Time(9, 50, 0)
>>> t1
09.50.00
>>> print(t1)
09:50:00
>>>
</source>
::* Note: if you have python code attached to both the __str__ and __repr__ special method, the print() function will use the string return by the __str__ method. If __str__ is not defined, the print() function will use the string return by __repr__.
 
:8. 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 lab7e
</source>
:9. Before proceeding, make certain that you identify all errors in lab7e.py. When the checking script tells you everything is OK - proceed to the next step.
== 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 code to the __add__ method''':<source lang="python"> def __add__(self, t2): return self.sum_times(t2)</source>:1. Copy lab7e.py to a new file called lab7f.py. Add the function definition for __add__() after the __str__() 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]$ python3Python 3.4.9 (default, Aug 14 2018, 21:28:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linuxType "help", "copyright", "credits" or "license" for more information.>>> from lab7f 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 + t210.51.01>>> x = t1 + t2>>> type(x)<class 'lab7f.Time'>>>> print(x)10:51:01</source>::* Note: If you get different results, please troubleshoot your lab7f.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 directoryls CheckLab7.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab7.pypython3 ./CheckLab7.py -f -v lab7f</source>:4. Before proceeding, make certain that you identify all errors in lab7f.py. When the checking script tells you everything is OK - proceed to the next step.
= Investigation III - Objects and Scope =
:'''Files to be submitted individually to Blackboard:'''
:: Name the output of <code>./CheckLab7.py -f -v </code> as lab7_[seneca_id].txt
:: Python script files for this lab: lab7a.py, lab7b.py, lab7c.py, lab7d.py, lab7e.py, and lab7dlab7f.py.
=Lab Review=
1,760
edits