gpt4 book ai didi

python - 清理 for 循环中断

转载 作者:行者123 更新时间:2023-12-03 20:48:30 28 4
gpt4 key购买 nike

你可以在python中创建一个在for循环退出时运行清理代码的迭代吗?就像是:

from random import randint

class Iterable:
def __iter__(self):
return self
def __next__(self):
return randint(1, 10)
def __iterclose__(self):
print("Clean up code")

for x in Iterable():
if x < 5:
break

# Prints "Clean up code"

最佳答案

我认为为了从可迭代协议(protocol)中受益,您应该让您的 Iterable 获得对停止条件的控制权。这个怎么样:


from random import randint


class Iterable:

def __init__(self, max):
self.i = 0
self.max = max

def __iter__(self):
return self

def __next__(self):
self.i += 1
if self.i > self.max:
self.cleanup()
raise StopIteration
return randint(1, 10)

def cleanup(self):
print("Clean up code")


for x in Iterable(5):
print(x)

关于python - 清理 for 循环中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61048877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com