Changes

Jump to: navigation, search

Rchan sandbox

287 bytes added, 20:15, 3 November 2019
Investigation II - Objects and Methods
: 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
1,760
edits

Navigation menu