• decorator & generator & iterator


    装饰器(decorator): @staticmethod @classmethod 都既可以使用类名访问,也可以使用对象名访问, 但classmethod在定义时需要cls参数

    生成器(generator): 任何包含yield语句的函数称为生成器。

    迭代器(iterator):一个实现了__iter__()方法的对象是可迭代的,一个实现了next方法的对象是迭代器。

    for item in Fibs():  next()方法和__iter__()方法缺一不可;__iter__()仅调用一次, next()调用多次(有多少个元素就调用多少次)

    decorator & generator是针对方法而言的,iterator是针对类(对象)而言的。

    #!/usr/bin/python3
    #coding:utf-8
    #如果想有中文注释就必须得有上面的语句
    
    #generator
    def countDown(n):
        print("Start to count from " + str(n))
        while n > 0:
            yield n
            n -= 1
        print("Done!")
    
    #iterator
    #迭代器(iterator):一个实现了__iter__()方法的对象是可迭代的,一个实现了next方法的对象是迭代器。
    #for item in Fibs():  next()方法和__iter__()方法缺一不可; __iter__()仅调用一次, next()调用多次(有多少个元素就调用多少次)
    class Fibs():
        def __init__(self):
            self.a = 1
            self.b = 1
    
        #Python2&Python3:如果没有next(), 有__iter__()提示如下错误
        #TypeError: iter() returned non-iterator of type 'Fibs'
        #def next(self):    #python2
        def __next__(self): #python3
            print("in next()")
            self.a, self.b = self.b, self.a + self.b
            return self.a
    
        #Python2&Python3:如果没有__iter__()(不管有没有next())则提示如下错误
        #TypeError: 'Fibs' object is not iterable
        def __iter__(self):
            print("in __iter__()")
            return self
    
    
    def main():
        for item in countDown(10):
            print(item)
    
        print("")   #newline
    
        print(type(Fibs))       #<type 'type'>
        print(type(Fibs()))     #<class '__main__.Fibs'>
    
        for fib in Fibs():
            if fib > 1000:
                print(fib)
                break
    
    if __name__ == '__main__':
        main()
    else:
        print("Being imported as a module.")

    Output:

    (py361scrapy133) lxw@lxw(11:11:20)~$ python3 generator_iterator.py 
    Start to count from 10
    10
    9
    8
    7
    6
    5
    4
    3
    2
    1
    Done!
    
    <class 'type'>
    <class '__main__.Fibs'>
    in __iter__()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    in next()
    1597

    References:

    python3:迭代器

  • 相关阅读:
    sublime text在Linux下build出现'ascii' codec can't decode byte 0xe4 in position 0的解决办法
    sublime text的verilog插件——verilog automatic
    Ubuntu Lucid Installation Guide
    vim之perlsupport的小修改
    python笔记
    sublime text中ctags使用注意事项
    2021年终总结
    wp7学习站点
    WPF中调用Winform控件
    Xen Cloud Platform 系列:NFS 存储库(四)
  • 原文地址:https://www.cnblogs.com/lxw0109/p/decorator_generator_iterator.html
Copyright © 2020-2023  润新知