修改包装器python打印以返回类型
从这段代码中,我了解到在Python中,print其实是一个包装函数,它是stdout
的write
方法的一个外壳。所以如果我给它一个返回类型,它也必须返回那个类型,对吧?那为什么我不能这样做呢?
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?
1 个回答
4
在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")