ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
>[success] # 实现反转函数 reversed ~~~ 1.实现一个类可以调用reversed 函数,需要构造__reversed__(self) ~~~ >[danger] ##### 案例 ~~~ class Countdown: def __init__(self, start): self.start = start def __iter__(self): n = self.start while n > 0: yield n n -=1 def __reversed__(self): n = 1 while n <= self.start: yield n n+=1 a = Countdown(10) for i in a: print(i) a = Countdown(10) for i in reversed(a): print(i) 打印结果: 10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10 ~~~