import sys
class HasWrite:
def __init__(self):
self.console = sys.stdout
self.store = []
def write(self, string):
self.store.append(string)
def input(self, str1, str2, str3):
sys.stdout = self
print(str1, str2, str3, sep='split', end='')
sys.stdout = self.console
hh = HasWrite()
hh.input('one', 'tow', 'three')
print(hh.store)
通过重定向sys.stdout,测试print函数的执行过程。执行结果,打印出来的hh.store是[‘one’, ‘split’, ‘tow’, ‘split’, ‘three’, ‘’],而不是[‘onesplittowsplitthree’]。
说明使用print函数时,会输出多次流,str1,然后再sep,然后再str2……最后再end,如果将sep或者end设置为’’,也会’'输出。而不是把所有东西组合在一起后一次性输出。