<div>On Wed, Aug 25, 2010 at 2:23 PM, Glenn Hutchings <span dir="ltr"><<a href="mailto:zondo42@gmail.com">zondo42@gmail.com</a>></span> wrote:</div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
On 25 Aug, 22:18, Ross Williamson <<a href="mailto:rosswilliamson....@gmail.com">rosswilliamson....@gmail.com</a>><br>
wrote:<br>
<div class="im">> Is there anyway in a class to overload the print function?<br>
><br>
> >> class foo_class():<br>
> >>      pass<br>
> >> cc = foo_class()<br>
> >> print cc<br>
><br>
> Gives:<br>
><br>
> <__main__.foo_class instance at ....><br>
><br>
> Can I do something like:<br>
><br>
> >> class foo_class():<br>
> >>     def __print__(self):<br>
> >>           print "hello"<br>
> >> cc = foo_class()<br>
> >> print cc<br>
><br>
> Gives:<br>
><br>
> hello<br>
<br>
</div>Yes.  Just define the __str__ method, like this:<br>
<br>
class foo_class():<br>
    def __str__(self):<br>
        return "hello"<br>
<div><div></div><div class="h5">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a></div></div></blockquote><div><br></div><div>I'd recommend looking at both the __str__ and __repr__ functions at <a href="http://docs.python.org/reference/datamodel.html">http://docs.python.org/reference/datamodel.html</a>.</div>
<div><br></div><div>Depending on your specific use case, its possible __repr__ may be perfered for you. </div></div><br>