如何使用方法结束循环?

时间:2015-05-12 15:16:58

标签: python

如何使用方法强制结束while循环?

class Test(object):

  def start(self):
    while True:
      self.stop()

  def stop(self):
    return break

obj=Test()
obj.start()

3 个答案:

答案 0 :(得分:3)

你应该保留一个标志,然后在while循环中检查它。

class Test(object):
    def __init__(self):
        self.running = False

    def start(self):
        self.running = True
        while self.running:
            self.running = not self.stop()


    def stop(self):
        return True

obj=Test()
obj.start()

如果你想立即停止,那么你需要打电话给休息:

def start(self):
    self.running = True
    while self.running:
        if self.stop():
            break;
        # do other stuff

答案 1 :(得分:2)

实现这一目标的最简单方法是提升StopIteration除外。这将立即停止循环,而不是RvdK的answer,它将在下一次迭代时停止。

class Test(object):

  def start(self):
    try:
      while True:
        self.stop()
    except StopIteration:
      pass

  def stop(self):
    raise StopIteration()

obj = Test()
obj.start()

答案 2 :(得分:0)

class Test(object):

  def start(self):
    while not self.stop():
        pass

  def stop(self):
    return True

obj=Test()
obj.start()

class Test(object):

  def start(self):
    while True:
        if self.stop():
            break

  def stop(self):
    return True

obj=Test()
obj.start()