面向对象-内置特殊方法-迭代和遍历。
# 1.for循环遍历
class Cat:
def __init__(self, num):
self.num = num
def __getitem__(self, item):
self.num += 1
if self.num >= 10: # 加个终止条件
raise StopIteration('遍历结束')
return self.num
c = Cat(2)
for i in c:
print(i)
# 2.迭代遍历:直接把列表转为可迭代对象返回出来给实例
class Cat:
def __init__(self, num):
self.num = num
def __iter__(self):
return iter(self.num) # 返回一个可迭代对象给下面的实例
list1 = [1, 2, 3, 4, 5, 6]
c = Cat(list1)
for i in c:
print(i)
# 3.迭代遍历:在内部使用next方法来实现可迭代
class Cat:
def __init__(self, num): # 这里num是整数
self.num = num
def __iter__(self): # 此方法一般用转换一个可迭代对象成为迭代器
# return iter(self.num)
return self # 这里的self实例是不可迭代的,所以要增加一个__next__方法来完善
def __next__(self):
self.num += 1 # 和上面的for循环不一样,这里的+=1是指指针每次偏移1,上面的for循环是下标变化
if self.num >= 10: # 加个终止条件
raise StopIteration('遍历结束')
return self.num
# list1 = [1, 2, 3, 4, 5, 6]
# b = Cat(list1)
c = Cat(1)
for i in c:
print(i)
# 上面的实例通过__next__()方法的加持,可以直接使用next在外界对对象进行迭代访问
class Cat:
def __init__(self, num): # 这里num是整数
self.num = num
def __iter__(self):
# return iter(self.num)
return self # 这里的self实例是不可迭代的,所以要增加一个__next__方法来完善
def __next__(self):
self.num += 1 # 和上面的for循环不一样,这里的+=1是指指针每次偏移1,上面的for循环是下标变化
if self.num >= 4: # 加个终止条件
raise StopIteration('遍历结束')
return self.num
c = Cat(1) # 从1到4
print(next(c))
print(next(c))
# print(next(b)) # StopIteration: 遍历结束
# 判断对象是不是迭代器:必须要实现__iter__()和__next__()两个方法
import collections.abc
print(isinstance(c, collections.abc.Iterator)) # 是不是迭代器:需要实现__iter__()和__next__()两个方法
print(isinstance(c, collections.abc.Iterable)) # 是不是可迭代的对象:只要实现__iter__这一个方法