2013-03-09 10 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