示例自定义范围类与内置的range函数不同,它不能重置或“重复使用”。如何使其具有可重用性?
def exampleCustomRange(stopExclusive):
for i in range(stopExclusive):
yield i
>> builtinRange = range(3)
>> [x for x in builtinRange]
[0, 1, 2]
>> [x for x in builtinRange]
[0, 1, 2] # See how this repeats on a second try? It is reusable or reset.
>>customRange = exampleCustomRange(3)
>> [x for x in customRange]
[0, 1, 2]
>> [x for x in customRange]
[] # See how this is now empty? It is not reusable or reset.
在上述REPL示例中展示的自定义范围类customRange第二次使用时,并不像内置的range函数那样可以重复、重置或重新使用。我希望让customRange的行为与内置的range保持一致。