Open main menu

CDOT Wiki β

Changes

OPS435 Python3 Lab 7

714 bytes added, 23:19, 12 March 2020
Part 3 - Operator overloading
:: A class is a type, a description of a thing, the definition of what it should look like (data attributes) and what we can do about it (function attributes).
:: An object is an instance of a class, an individual entity described by a class, a specific stuff with properties (aka attributes) defined by a class.
:: Type The exact definition of the type and what you would expect to store in objects of that type is up to you - the programmer. You would want to design your classes so that you can manage data in your program/script/application as easily as possible.
:: A few points about the mechanics of implementing classes:
:::* A class name typically starts with a capital letter, and object names should start with a lowercase letter.
==Reference==
:*Time object code: from '''Think Python''' by Allen B. Downey: [http://greenteapress.com/thinkpython2/html/thinkpython2017.html Chapter 16 ] and [http://greenteapress.com/thinkpython2/html/thinkpython2018.html Chapter 17]:*Date Data object : [https://docs.python.org/3/reference/datamodel.html#special-method-names special method name]
=Investigation I: Objects and Functions=
self_sec = self.time_to_sec()
t2_sec = t2.time_to_sec()
sum = sec_to_time(sec1 self_sec + sec2t2_sec)
return sum
time_seconds = self.time_to_sec()
nt = sec_to_time(time_seconds + seconds)
timeself.hour, timeself.minute, timeself.second = nt.hour, nt.minute, nt.second
return None
: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_datevalid_time(), 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/
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 lab7e.py. Make sure that the '''def __str__(self):''' line has the same indentation level as the __init__() function.
<lab7e.Time object at 0x7f830b498be0>
>>> print(t1)
09.:50.:00
>>> t1.format_time()
'09:50:00'
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.
== 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):
: Sometimes you want to have an object accessible from anywhere in your program, including inside and outside any functions. Here's an example:
:1. '''[https://ict.senecacollege.ca/~raymond.chan/ops435/labs/lab7/lab7h.py lab7h.py]''' - global scope <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
</source>
: 2. Note that the same thing is printed over and over because the '''schoolName''' object is defined outside a function which makes it global which makes it accessible from anywhere.
: 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. '''[https://ict.senecacollege.ca/~raymond.chan/ops435/labs/lab7/lab7i.py lab7i.py]''' - global keyword <source lang="python">
#!/usr/bin/env python3
# Student ID: [seneca_id]
print('print() in main on schoolName:',schoolName)
</source>
:* The execution of the script '''lab7i.py''' shown above should give youryou the following:<source lang="bash">
[rchan@centos7 lab7]$ python3 lab7i.py
print() in main on schoolName: Seneca
print() in main on schoolName: SSDO
</source>
::*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
print() in main on schoolName: SSDO
</source>
 
: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 lab7i
</source>
:7. Before proceeding, make certain that you identify all errors in lab7i.py. When the checking script tells you everything is OK - proceed to the next step.
== Object/Instance Scope ==
14
edits