我读了蟒蛇菜谱第二,在“CHAP 2.13使用C++ - 样的iostream语法“一个样品,我试着去了解如何自我作品在超载蟒蛇运算符“<<”作为C++的iostream
class IOManipulator(object):
def __init__(self, function=None):
self.function = function
def do(self, output):
self.function(output)
def do_endl(stream):
stream.output.write('\n')
stream.output.flush()
endl = IOManipulator(do_endl)
# my understanding, all above is about make a newline and flush sys.stdout,
class OStream(object):
def __init__(self, output=None):
if output is None:
import sys
output = sys.stdout
self.output = output
self.format = '%s'
def __lshift__(self, thing):
if isinstance(thing, IOManipulator):
thing.do(self)
# It make no sense to me, why the function belongs to
# another class's instance need call (self)
else:
self.output.write(self.format % thing)
self.format = '%s' # <- is it necessary? seems to be not.
return self # <- why return a "self" here?
# If comment this line out,
# python raise a TypeError when execute to the "<< 1"
# TypeError: unsupported operand type(s) for <<: 'NoneType' and 'int'
def example_main():
cout = OStream()
cout << "The average of " << 1 << " and " << 3 << " is " << (1+3)/2 << endl
if __name__ == '__main__':
example_main()
# emits:
#> The average of 1 and 3 is 2
的代码。“自我”是<__main__.OStream object at 0x7fc28cd92410>
,我知道这是ostream的类的实例,也许可以作为C指针。
'回报self'是因为你使用所需的''<<在第一次''<<操作的输出等等... –
时注意如果一个函数错过了'return'蟒蛇做了'返回None。因此,你看到的错误('<<'返回一个'None'和'None << x'没有定义)。 – Bakuriu
无论如何'返回自我'是**不是**严格要求。你必须把'return something'放回去,但'something'可能是别的东西,就像一个新的'OStream'。 – Bakuriu