2015-11-08 80 views
-1

我读了蟒蛇菜谱第二,在“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指针。

+1

'回报self'是因为你使用所需的''<<在第一次''<<操作的输出等等... –

+0

时注意如果一个函数错过了'return'蟒蛇做了'返回None。因此,你看到的错误('<<'返回一个'None'和'None << x'没有定义)。 – Bakuriu

+0

无论如何'返回自我'是**不是**严格要求。你必须把'return something'放回去,但'something'可能是别的东西,就像一个新的'OStream'。 – Bakuriu

回答

2

我会回答你提出的问题评论:


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) 

您通过self(输出流)到thing(这将是一个IOManipulatorendl操作),从而使IOManipulator类可以在执行功能(见下文,IOManipulator.do)输出流。

def do(self, output): 
    self.function(output) 

混乱的最高金额,第一self在这个片段是不是你传递给它的OStreamself!你通过selfthing.do被设置为output变量。


return self # <- why return a "self" here? 

您这里返回OStream实例,因此您可以连锁经营。需要注意的是Python解析行a << b << c(a << b) << c。该(a << b)部件需要以那么能够做到就可以了<< c和意义返回其更新自我。如果你对此有何评论return self出来,你最终None << c因为那么函数将返回None


self.format 

我不确定什么作者的意图与此,似乎没有必要。行self.output.write(self.format % thing)也可能被写为self.output.write(str(thing))


一点题外话:这可能是你能如何实现一个新的运营商的例子,但是这个具体的操作是非常,Python的:它会导致真正的丑陋和混乱的代码。在现实世界中,尝试使用语言已有的功能。