1,760
edits
Changes
→Part 2 - Special object methods
</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 look like 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. 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 lab7d.py and test it in an interactive Python shell:<source lang="bash">
[rchan@centos7 lab7]$ python3