如何重载打印功能以扩展其功能? [英] How to overload print function to expand its functionality?

查看:61
本文介绍了如何重载打印功能以扩展其功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以覆盖内置函数 print 以便以下语句同时写入控制台和文件.

I am wondering if the build-in function print could be overridden so that the following statement will write to the console and a file at the same time.

print("test0","test1","test2",sep='\n') 

另外,请问是否可以修改内置print函数的源代码?

Also, may I know if it is possible to modify the source code of the build-in print function?

推荐答案

您可以使用 write 方法创建一个类,并且在该方法中您可以 print printcode>stdout 以及 write 到文件中.

You can create a class with a write method and inside of that method you can print both stdout as well as write to the file.

import sys

class A(object):
    def __init__(self, f):
        self.f = open(f, 'w') 

    def __enter__(self):
        return self   # return instance of A which is assign to `f`.

    def write(self, text):
        sys.stdout.write(text)  # print to the shell
        self.f.write(text) # write in the file

    def __exit__(self, *args):
        self.f.close()
        return True

with A('foo.txt') as f:
    print("test0","test1","test4",sep='\n', file=f) #`file = f` calls `write` method

这篇关于如何重载打印功能以扩展其功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆