Overload print

Glenn Hutchings zondo42 at gmail.com
Wed Aug 25 17:23:41 EDT 2010


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"



More information about the Python-list mailing list