这不是递归。发生的情况是您的
write函数被调用了两次,一次调用了您期望的文本,第二次调用了just
'n'。尝试这个:
import sysclass 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')在上面的代码中,我所做的是将新行字符添加到第一次调用中传递的文本中,并确保由print语句进行的第二次调用(用于打印新行)不会打印任何内容。
现在尝试注释掉前两行,看看会发生什么:
def write(self, text): #text = text.rstrip() #if len(text) == 0: return self.old_stdout.write('custom Print--->' + text + 'n')


