Changes

Jump to: navigation, search

Rchan sandbox

839 bytes added, 17:02, 3 November 2019
Part 2 - Special object methods
: Each programmer-defined object has a few special methods which can be used to manipulate the object, the one we already know is the '''__init__''' method, which python refers it as the object constructor, and we can associate code to this method in the class definition.
: In this part, we are going to investigate and study the '''__str__''' and '''__repr__''' special methods.
::*'''Associate the following code to the __str__''' method for the Time class in lab7d.py: <source lang="python">
def __str__(self):
'''return a string representation for the object self'''
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lab7d1 lab7d import *
>>> t1 = Time(9,50,0)
>>> t1
<lab7d1lab7d.Time object at 0x7f830b498be0>
>>> print(t1)
09.50.00
::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.
::6. * '''Associate the following code to the __repr__''' method for the Time class in lab7d.py: <source lang="python">
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 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)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lab7d2 import *
>>> t1 = Time(9, 50, 0)
>>> t1
09.50.00
>>> print(t1)
09:50:00
>>>
</source>
::* Note: if you have python code attached to both the __str__ and __repr__ special method, the print() function will use the string return by the __str__ method. If __str__ is not defined, the print() function will use the string return by __repr__.
== Part 3 - Operator overloading ==
1,760
edits

Navigation menu