Changes

Jump to: navigation, search

Rchan sandbox

7 bytes removed, 18:30, 3 November 2019
Part 2 - Special object methods
return '%.2d:%2d:%2d' % (self.hour, self.minute, self.second)
</source>
::1. Add the function definition for __str__() after the __init__() function in lab7d.py. Make sure that the '''def __str__(self):''' 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)
>>>
</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 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 attached code to this function to tell the python interpreter what we want the object to appear on an interactive shell.
::* '''Associate the following code to the __repr__''' method for the Time class in lab7d.py: <source lang="python">
def __repr__(self):
return '%.2d.%2d.%2d' % (self.hour, self.minute, self.second)
</source>
::6. Add the function definition for __repr__() after the __str__() function in lab7d.py. Make sure that the '''def __repr__(self):''' line has the same indentation level as the __init__() function.::7. 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)
1,760
edits

Navigation menu