装饰器(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: