简体   繁体   English

如何覆盖内置方法“print()”

[英]How to override the builtin method "print()"

I need to customize the print() , so that it does something else besides printing what I want.我需要自定义print() ,以便它除了打印我想要的东西之外还可以做其他事情。 Is there a way to override it?有没有办法覆盖它?

Here is A Page That Will Help You With Overriding Functions!是一个可以帮助您使用覆盖功能的页面!

Here is A Way To Override print !这是一种覆盖print的方法! (Making a New print ) (制作新的print

Code:代码:

from __future__ import print_function

try:
    import __builtin__
except ImportError:
    import builtins as __builtin__

def print(*args, **kwargs):
    """My custom print() function."""
    __builtin__.print('your text')
    return __builtin__.print(*args, **kwargs)

print()打印()

Output: your text Output: your text

The Line __builtin__.print('your text') would Print 'Your Text', you can put other function Also Instead of Print, it would Print Your Given Text also As The Return Line Says It to, it used the built in print function! __builtin__.print('your text')行将打印'Your Text',您可以放置其他 function 而不是打印,它也会打印您的给定文本,正如返回行所说,它使用内置的打印功能!

The Second Thing That you can Do is That You Can Remove The Return Line so The Function wouldn't Print Anything To The Console您可以做的第二件事是您可以移除返回线,这样 Function 就不会在控制台上打印任何内容

Hope This Helps希望这可以帮助

one option is to use contextlib.redirect_stdout :一种选择是使用contextlib.redirect_stdout

from contextlib import redirect_stdout

with open('file.txt', 'a') as file, redirect_stdout(file):
    print('hello')

if you need both printing and saving to a file, this may work:如果您需要打印和保存到文件,这可能有效:

from contextlib import redirect_stdout
from sys import stdout
from io import StringIO

class MyOutput(StringIO):
    def __init__(self, file):
        super().__init__()
        self.file = file

    def write(self, msg):
        stdout.write(msg)
        self.file.write(msg)

with open('file.txt', 'a') as file, redirect_stdout(MyOutput(file=file)):
    print('hello')

You can override the print() method but you have to create class and then override the " str " dunder method (print() uses " str " implementation in backend).您可以覆盖 print() 方法,但必须创建 class 然后覆盖“ str ” dunder 方法(print() 在后端使用“ str ”实现)。 Here is the code.这是代码。

a = 2
print(a)

class abc:
    def __init__(self,x):
        self.x = x
    def __str__(self):
        return "The value is " + str(self.x)

a = abc(2)
print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM