Python 的 自定义迭代器
等级 5287 次按键
这创建了一个实现__iter__和__next__的自定义迭代器类。迭代器协议允许对象在for循环中使用。
Python 代码
# 定义一个可以迭代的自定义类1class Range: # 构造函数接受开始和结束值2 def __init__(self, start, end):3 self.start = start4 self.end = end5 # __iter__在迭代开始时被调用6 def __iter__(self): # 将当前位置初始化为起始值7 self.current = self.start # 返回self作为迭代器对象8 return self9 # __next__在每次迭代时被调用10 def __next__(self): # current到达end时停止(不包含end)11 if self.current >= self.end:12 raise StopIteration # 递增前保存当前值13 val = self.current14 self.current += 1 # 返回保存的值15 return val16 # 在for循环中使用自定义迭代器17for n in Range(1, 4):18 print(n)运行结果
1 2 3
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
_× 12.× 8:× 6=× 6(× 5)× 5,× 3+× 1>× 1