Changes

Jump to: navigation, search

OPS445 Online Lab7

105 bytes added, 16:35, 14 November 2023
added double 02d to f-string: fix for new version of python
def format_time(t):
"""Return time object (t) as a formatted string"""
return f'%{t.2dhour:%.2d02d}:%.2d' % (t.hour, {t.minute, :02d}:{t.second):02d}'
def sum_times(t1, t2):
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7a
</source>
</source>
:7. The result is not correct! So we have to modify and update the change_time() function so that it can handle positive and negative value correctly. The following steps are necessary:
::(a) We must first add code to check on the '''second''' attribute of the time object to make sure that it is not less than zero. If it is, we must borrow one from the '''minute''' attribute and add 60 to the '''second''' attribute. We have to repeat this checking until the '''second''' attribute is no long longer less than zero.<source lang="python"> while time.second < 0: time.minute -= 1 time.second += 60</source>::(b) We then have to add code to check on the '''minute''' attribute. If it is less than zero, we must borrow 1 from the 'hour' attribute and add 60 to the '''minute''' attribute. We have to repeat this checking until the '''minute''' attribute is no long longer less than zero.<source lang="python"> while time.minute < 0: time.hour -= 1 time.minute += 60</source>:8. After updating the change_time() function with the above additional codetasks, save the file and test it again in a Python interactive shell by importing the new version of the function.<source lang='bash'>
[rchan@centos7 lab7]$ python3
Python 3.4.9 (default, Aug 14 2018, 21:28:57)
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7b
</source>
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7c
</source>
# Student ID: [seneca_id]
class Time:
"""Simple object type for time of the day. data attributes: hour, minute, second function attributes: __init__, __str__, __repr__ time_to_sec, format_time, change_time, sum_time """ def __init__(self,hour=12,minute=0,second=0): """constructor for time object""" self.hour = hour self.minute = minute self.second = second def format_time(self): """Return time object (t) as a formatted string""" return f'%{self.2dhour:%02d}:{self.2dminute:02d}:%{self.2dsecond:02d}' % def sum_times(self.hour, selft2): """Add two time objests and return the sum.minute, self""" """Change this to become object method for our Time object (refer to lab7c.secondpy and change_time() method below)""" return sum
def sum_timeschange_time(self, t2seconds): """Add two time objests and return the sum.""" sum = Time(0,0,0) self_sec time_seconds = self.time_to_sec() t2_sec nt = t2.time_to_secsec_to_time(time_seconds + seconds) sum self.hour, self.minute, self.second = sec_to_time(self_sec + t2_sec)nt.hour, nt.minute, nt.second return sumNone
def change_timetime_to_sec(self, seconds): time_seconds = self.time_to_sec() '''convert a time object to a single integer representing the nt = sec_to_time(time_seconds + number of seconds)from mid-night''' minutes = self.hour, * 60 + self.minute, seconds = minutes * 60 + self.second = nt.hour, nt.minute, nt.second return Noneseconds
def time_to_sec(self): '''convert a time object to a single integer representing the number of seconds from mid-night''' minutes = self.hour * 60 + self.minute seconds = minutes * 60 + self.second return seconds  def valid_time(self): """check for the validity of the time object attributes: 24 > hour > 0, 60 > minute > 0, 60 > second > 0 """ if self.hour < 0 or self.minute < 0 or self.second < 0: return False if self.minute >= 60 or self.second >= 60 or self.hour >= 24: return False return True
def sec_to_time(seconds):
</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, and change '''sum_times()''' function from lab7c.py to become object method for our Time object (refering to change_time() method above might be helpful).
:2. Save the file, and test the new time object in an interactive Python shell: <source lang="bash">
[rchan@centos7 lab7]$ python3
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7d
</source>
def __str__(self):
'''return a string representation for the object self'''
return f'%{self.2dhour:%.2d02d}:%.2d' % (self.hour, {self.minute, :02d}:{self.second) :02d}'
</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 lab7e.py. Make sure that the '''def __str__(self):''' line has the same indentation level as the __init__() function.
def __repr__(self):
'''return a string representation for the object self'''
return '%.2d.%.2d.%.2d' % (self.hour'just instead of ':', selfyou are required use the '.minute, self' in the formatting string.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.
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7e
</source>
== 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
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7f
</source>
: Try the following code. Have each in a separate Python file.
: '''Local scope(lab7g.py)''': <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
: Sometimes you want to have an object accessible from anywhere in your program, including inside and outside any functions. Here's an example:
:1. '''Global scope(lab7h.py)''': <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
:3. Python has one weird quirk when it comes to global scope: if you assign something to an existing object inside a function - it will assume you want to create a new object in that function's local scope. That will hide the global object inside the function unless you declare it explicitly with the global keyword:
:4. '''Global keyword(lab7i.py)''': <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
::*Note that the function1() call does not modify the global '''schoolName''' object but function2() does.
:5 . As the last task for this lab: modify the script above so that it would print the following, by changing only the scope of some objects. Save the program as '''lab7i.py''': <source lang="bash">
print() in main on schoolName: Seneca
print() in function1 on schoolName: SICT
cd ~/ops445/lab7/
pwd #confirm that you are in the right directory
ls CheckLab7.py || wget 'https://ictgithub.senecacollege.cacom/~eric.brauersenecaops445/ops445lab7-template/labsblob/LabCheckScriptsmaster/CheckLab7.py?raw=true' -O CheckLab7.py
python3 ./CheckLab7.py -f -v lab7i
</source>

Navigation menu