美文网首页
Python: yeild的使用理解

Python: yeild的使用理解

作者: f1972ad6d3bf | 来源:发表于2018-01-05 23:06 被阅读82次

    目前从网上找到的有关yeild最容易理解的解释,写的非常通俗易懂。
    https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/

    yeild其实就是一个迭代生成器,和其它笨方法相比,最大的优势就是节省内存空间。。

    有关yeild类的实现方法

    在类的实现方法中,实现了一个的一个迭代器的函数iter.

    class Fab(object): 
     
       def __init__(self, max): 
           self.max = max 
           self.n, self.a, self.b = 0, 0, 1 
     
       def __iter__(self): 
           return self 
     
       def next(self): 
           if self.n < self.max: 
               r = self.b 
               self.a, self.b = self.b, self.a + self.b 
               self.n = self.n + 1 
               return r 
           raise StopIteration()
    

    如何调用:

    for n in Fab(5): 
       print n 
    

    yeild的等价方法(更为简洁的方法)

    def fab(max): 
        n, a, b = 0, 0, 1 
        while n < max: 
            yield b 
            # print b 
            a, b = b, a + b 
            n = n + 1 
    

    调用方法

    for n in fab(5): 
       print n 
    

    相关文章

      网友评论

          本文标题:Python: yeild的使用理解

          本文链接:https://www.haomeiwen.com/subject/jqrenxtx.html