overload print python overload print python python python

overload print python


For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.

In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:

from __future__ import print_function# This must be the first statement before other statements.# You may only put a quoted or triple quoted string, # Python comments, other future statements, or blank lines before the __future__ line.try:    import __builtin__except ImportError:    # Python 3    import builtins as __builtin__def print(*args, **kwargs):    """My custom print() function."""    # Adding new arguments to the print function signature     # is probably a bad idea.    # Instead consider testing if custom argument keywords    # are present in kwargs    __builtin__.print('My overridden print() function!')    return __builtin__.print(*args, **kwargs)

Of course you'll need to consider that this print function is only module wide at this point. You could choose to override __builtin__.print, but you'll need to save the original __builtin__.print; likely mucking with the __builtin__ namespace.


Overloading print is a design feature of python 3.0 to address your lack of ability to do so in python 2.x.

However, you can override sys.stdout. (example.) Just assign it to another file-like object that does what you want.

Alternatively, you could just pipe your script through the the unix tee command. python yourscript.py | tee output.txt will print to both stdout and to output.txt, but this will capture all output.


class MovieDesc:    name = "Name"    genders = "Genders"    country = "Country" def __str__(self):#Do whatever you want here        return "Name: {0}\tGenders: {1} Country: {2} ".format(self.name,self.genders,self.country))