class Reverse: def __init__(self, string): self.__string = string self.__index = len(string) def __iter__(self): return self def __next__(self): self.__index -= 1 return self.__string[self.__index] revstr = Reverse('Python') for c in revstr: print(c,end=" ")執行結果為:
n o h t y P n o h t y P Traceback (most recent call last):
File "C:UsersmengmaDesktopdemo.py", line 11, in <module>
for c in revstr:
File "C:UsersmengmaDesktopdemo.py", line 9, in __next__
return self.__string[self.__index]
IndexError: string index out of range
class Reverse: def __init__(self, string): self.__string = string self.__index = len(string) def __iter__(self): return self def __next__(self): if self.__index == 0: raise(StopIteration) self.__index -= 1 return self.__string[self.__index] revstr = Reverse('Python') for c in revstr: print(c,end=" ")執行結果為:
n o h t y P