for... in...可以通过实现 Python 中的 iter 和 next 方法来实现。例如,定义一个新的类,名为 MyRange,像 Python 中的 range 一样: class MyRange: def __init__(self, start, end): self.value = start self.end = end def __iter__(self): return self def __next__(self): if self.value >= self.end: raise StopIteration current = self.value self.value += 1 return current