Overload print
Chris Kaynor
ckaynor at zindagigames.com
Wed Aug 25 17:43:51 EDT 2010
On Wed, Aug 25, 2010 at 2:23 PM, Glenn Hutchings <zondo42 at gmail.com> wrote:
> On 25 Aug, 22:18, Ross Williamson <rosswilliamson.... at gmail.com>
> wrote:
> > Is there anyway in a class to overload the print function?
> >
> > >> class foo_class():
> > >> pass
> > >> cc = foo_class()
> > >> print cc
> >
> > Gives:
> >
> > <__main__.foo_class instance at ....>
> >
> > Can I do something like:
> >
> > >> class foo_class():
> > >> def __print__(self):
> > >> print "hello"
> > >> cc = foo_class()
> > >> print cc
> >
> > Gives:
> >
> > hello
>
> Yes. Just define the __str__ method, like this:
>
> class foo_class():
> def __str__(self):
> return "hello"
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I'd recommend looking at both the __str__ and __repr__ functions at
http://docs.python.org/reference/datamodel.html.
Depending on your specific use case, its possible __repr__ may be perfered
for you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100825/b388c9fd/attachment-0001.html>
More information about the Python-list
mailing list