[Tutor] Is this correct?
Kent Johnson
kent37 at tds.net
Sun Apr 16 13:28:34 CEST 2006
Hoffmann wrote:
> class Time:
> def __init__(self, hours = 0, minutes = 0, seconds =
> 0):
> self.hours = hours
> self.minutes = minutes
> self.seconds = seconds
>
> def printTime(self): # By convention, the first
> parameter of a method is called self.
> '''printTime:
>
> Prints the time.'''
> print str(self.hours) + ":" + str(self.minutes) +
> ":" + str(self.seconds)
Instead of writing a method that prints the Time, a more flexible
approach is to write a method that returns a string representation of
the Time. If you call the method __str__(), it is recognized by Python
and used automatically by print statements. For example:
In [1]: class Test(object):
...: def __init__(self, value):
...: self.value = value
...: def __str__(self):
...: return 'Test(%s)' % self.value
...:
...:
In [2]: t1=Test(3)
In [3]: print t1
Test(3)
Writing a __str__() method gives the caller the flexibility to format
the result further, such as printing two Tests on one line:
In [4]: t2 = Test(4)
In [5]: print t1, t2
Test(3) Test(4)
By the way, __str__ is an example of a "special method" - a method that
is recognized by the Python runtime and used to implement bits of Python
functionality. When you write
print x
this becomes
print str(x)
which is implemented as
print x.__str__()
You can learn more about special methods here:
http://docs.python.org/ref/specialnames.html
Kent
More information about the Tutor
mailing list