# 容器
class A:
def __init__(self):
self.items = [1, 2]
def __contains__(self, item):
return item in self.items
a = A()
print(1 in a) # True
print(2 in a) # True
print(3 in a) # False
# 迭代器
class B:
"""A 实现了迭代器协议 它的实例就是一个迭代器"""
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self):
print('__iter__')
return self
def __next__(self):
if self.idx < self.n:
val = self.idx
self.idx += 1
return val
else:
raise StopIteration()
# 迭代元素
a = B(3)
next(a)
for i in a:
print(i)
# 再次迭代 没有元素输出 因为迭代器只能迭代一次
for i in a:
print(i)
for i in B(3):
print(i)
g = (i for i in range(5))
print(g)
print(iter(g))
for i in g:
print(i)
# 生成器
def gen(n):
for i in range(n):
yield i
# 创建一个生成器
g = gen(5)
for i in g:
print(i)
容器、迭代器、生成器
最新推荐文章于 2024-09-05 11:10:46 发布