您在這裡

The __str__ method

8 九月, 2015 - 10:43

__str__ is a special method, like __init__, that is supposed to return a string representation of an object.

For example, here is a str method for Time objects:

# inside class Time:
 
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

When you print an object, Python invokes the str method:

>>> time = Time(9, 45)>>> print time09:45:00

When I write a new class, I almost always start by writing __init__, which makes it easier to instantiate objects, and __str__, which is useful for debugging.

Exercise 17.3. Write astrmethod for thePointclass. Create a Point object and print it.