[Tutor] How to call a method with a print statement?
Wayne Werner
waynejwerner at gmail.com
Thu Nov 12 14:17:39 CET 2009
On Thu, Nov 12, 2009 at 6:00 AM, Kent Johnson <kent37 at tds.net> wrote:
> <snip>
>
> Defining __repr__ will give the custom representation when you just
> give the name of the object:
>
> In [5]: class Foo2():
> ...: def __repr__(self):
> ...: return "I'm a Foo2"
> ...:
> ...:
>
> In [6]: f2=Foo2()
>
> In [7]: f2
> Out[7]: I'm a Foo2
>
> In [8]: print f2
> I'm a Foo2
>
>
Which can be surprisingly useful in certain cases (I've used it for
debugging).
class Foo2:
def __init__(self):
self.name = 'This is my name'
self.value = 'This is my value'
def __repr__(self):
return "Name: %s\nValue: %s" % (self.name, self.value)
In [2]: a = Foo2()
In [3]: a
Out[3]:
Name: This is my name
Value: This is my value
In [4]: print a
------> print(a)
Name: This is my name
Value: This is my value
HTH,
Wayne
--
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091112/901f5547/attachment-0001.htm>
More information about the Tutor
mailing list