【问题标题】:Extend the functionality of the print statement/function扩展打印语句/函数的功能
【发布时间】:2014-10-24 12:53:21
【问题描述】:

我想打印特定规格的东西,例如使用 str() 方法而不是 repr() 打印容器([]{}())。编写一个可以做到这一点的函数很简单

def str_print_list(alist):
    print "["+", ".join(map(str, alist))+"]"

但如果我可以扩展或装饰 print statementprint() function(在 Python 2.7 中),那就太好了

我可以做类似这样的事情,它适用于 python 3(在http://www.compileonline.com/execute_python3_online.php 在 Python 3.2.3 中测试)

class foo(): 
    def __str__(self):
        return "String"
    def __repr__(self):
        return "Repr"

print([foo()])

def my_decorator(func):
    def inner(alist):
        if isinstance(alist, list):
            return func("["+", ".join(map(str, alist))+"]")
        else:
            return func(alist)
    return inner

print = my_decorator(print)
print([foo()])

这给了我一个输出

[Repr]
[String]

但在

处给我一个 python 2.7.6 中的语法错误
print = my_decorator(print)

直到我导入

from __future__ import print_function

这是有道理的,因为(据我所知)语句不能被修饰或重新分配。

所以我的问题是

  1. 是否可以装饰打印语句,这样我就不必导入函数了?
  2. 这是一个好主意,还是我应该更明确地使用我的str_print_list() 函数?在这种情况下,我知道事实上这将是我个人使用的,主要用于调试

【问题讨论】:

  • 在 Python 2.x 中,print 不是函数而是语言结构。您需要在 Python 2.x 中执行 from __future__ import print_function 才能获得 Python 3.x 风格的 print 函数。
  • @isedev 是的,我在我的问题中这么说(接近底部)。我想明确一点,如果可能的话,我正在寻求一种扩展语句的方法,否则只是导入的函数
  • 好吧,我换一种说法:不能装饰语句,所以必须导入函数。
  • 您可以为sys.stdout 安装一个自定义处理程序,该处理程序将拦截打印调用,在它们通过管道传输到标准输出之前对其进行更改。这适用于所有 python 版本。一个例子是我在这里所做的:stackoverflow.com/questions/25512442/…
  • @roippi 所以我只需将 colorize 函数替换为使列表更清晰的函数,然后再加入一些 if 语句?

标签: python python-2.7 python-3.x decorator


【解决方案1】:
  1. 不,不能更改语句。
  2. 没有。处理这个问题的方法是创建自己的 list 并传递它——这正是继承的目的。

像这样:

class MyPrintableList(list):
    def __repr__(self):
        return "[{}]".format(",".join(self))

print MyPrintableList([foo()])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2018-09-09
    • 1970-01-01
    相关资源
    最近更新 更多