Can print() be reloaded for a user defined class?
r
rt8396 at gmail.com
Sat Sep 19 23:06:18 EDT 2009
On Sep 19, 9:53 pm, Peng Yu <pengyu... at gmail.com> wrote:
(snip)
> I want to understand the exact meaning of the last line ('__repr__ =
> __str__'). Would you please point me to the section of the python
> manual that describes such usage.
simple i assined any call to __repr__ to the __str__ methods.
>>> class Test():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Test(%s, %s)' %(self.x, self.y)
>>> t = Test(1,2)
>>> t
<__main__.Test instance at 0x02CD15D0>
>>> print t
Test(1, 2)
>>> repr(t)
'<__main__.Test instance at 0x02CD15D0>'
>>> class Test():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Test(%s, %s)' %(self.x, self.y)
__repr__ = __str__
>>> t = Test(3,4)
>>> t
Test(3, 4)
>>> print t
Test(3, 4)
>>> repr(t)
'Test(3, 4)'
it's good for command line testing since you will not need to call
print < instance > all the time. You may not always want to use this
binding of __repr__ to __str__, but it has some effective uses ;)
More information about the Python-list
mailing list