alex.kapps at web.de
Wed Aug 25 23:42:42 CEST 2010
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
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
In : class Foo(object):
....: def __str__(self):
....: return "foo"
In : f = Foo()
In : print f
More information about the Python-list