2013-03-09 41 views
1

我从这段代码得到的是,打印在python是writestdout方法的包装功能,所以如果我给它一个返回类型它必须返回,以及,对吧?那为什么我不能那样做?修改包装python打印返回类型

import sys 
class CustomPrint(): 
    def __init__(self): 
     self.old_stdout=sys.stdout 

    def write(self, text): 
     text = text.rstrip() 
     if len(text) == 0: return 
     self.old_stdout.write('custom Print--->' + text + '\n') 
     return text 
sys.stdout=CustomPrint() 
print "ab" //works 
a=print "ab" //error! but why? 

回答

3

在python2.x,print声明。所以,a = print "ab"是非法的语法。试试print "ab"

在python3中,print是一个函数 - 所以你会写:a = print("ab")。请注意,从python2.6开始,您可以通过from __future__ import print_function访问python3的print函数。

最终,你想要的是一样的东西:

#Need this to use `print` as a function name. 
from __future__ import print_function 
import sys 

class CustomPrint(object): 
    def __init__(self): 
     self._stdout = sys.stdout 
    def write(self,text): 
     text = text.rstrip() 
     if text: 
      self._stdout.write('custom Print--->{0}\n'.format(text)) 
      return text 
    __call__ = write 

print = CustomPrint() 

a = print("ab") 
+0

'A =打印( “AB”)'不会帮助,因为'print'总是返回'None'。 OP应该使用一个自定义函数。 – bereal 2013-03-09 16:22:45

+0

@bereal - 当然,'a'会是'None',但程序会执行并写入'sys.stdout'(这是我认为OP想要的东西)。我不完全确定OP期望'a'在这里...... – mgilson 2013-03-09 16:24:06

+3

from'return text' in'write'我假设他想要''ab“'。 – bereal 2013-03-09 16:27:17