我讀了蟒蛇菜譜第二,在「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