Overload print

John Roth johnroth1 at gmail.com
Thu Aug 26 15:29:25 EDT 2010


On Aug 25, 3:42 pm, Alexander Kapps <alex.ka... at web.de> wrote:
> Ross Williamson wrote:
> > Hi All
>
> > Is there anyway in a class to overload the print function?
>
> In Python <= 2.x "print" is a statement and thus can't be
> "overloaded". That's exactly the reason, why Python 3 has turned
> "print" into a function.
>
> >>> class foo_class():
> >>>     def __print__(self):
> >>>           print "hello"
>
> >>> cc = foo_class()
> >>> print cc
>
> > Gives:
>
> > hello
>
> Hmm, on what Python version are you? To my knowledge there is no
> __print__ special method. Did you mean __str__ or __repr__ ?
>
> > I'm looking at finding nice way to print variables in a class just by
> > asking to print it
>
> In Python3 you *can* overload print(), but still, you better define
> __str__() on your class to return a string, representing what ever
> you want:
>
> In [11]: class Foo(object):
>     ....:     def __str__(self):
>     ....:         return "foo"
>     ....:
>     ....:
>
> In [12]: f = Foo()
>
> In [13]: print f
> foo

Maybe what the OP really wants is the format() method on a string?
That gives a very rich set of override options, at the expense of not
using the print statement/method, including the ability to define your
own formatting language for a class.

John Roth



More information about the Python-list mailing list