2017-09-18 32 views
0

比方说,我有一个类:从类中停止程序在Python

class A: 
    def command(self, input): 
     if command == 'test1': 
      do something... 
     if command == 'quit': 
      #stop the program 

和类外我开始while循环:

if __name__ == "__main__" 
    lst = A() 
    while True: 
     command = input("Enter an option:") 
     lst.command(command) 

我被困在点如果命令是“退出”,我需要停止整个程序的运行。我现在面临的问题是,由于我在课堂外发起了一个while循环,我该如何'假'循环才能停止整个程序?

我正在寻找一个休息方法或可能创建另一个函数来完全退出程序,但不是sys()quit()方法,我猜我不允许这样做。

+1

['sys.exit()'](https://docs.python.org/3/library/sys.html#sys.exit) – Nayuki

回答

1

在班级的任何地方使用sys.exit()或类似的“核”功能通常是一个坏主意。 (所以有一个while True循环。)相反,让循环自然和优雅地打破。

首先,您的command必须在收到"quit"时返回一个标记。哨兵的价值取决于应用程序;让我们说这是None

if command == 'quit': 
    return None 

循环应该看的返回值,并打破返回定点时:

lst = A() 
command = input("Enter an option:") 
while command is not None:   
    lst.command(command) 
    command = input("Enter an option:") 
1

你可以只移动command功能外quit命令。

class A: 
    def command(self, inp): 
     pass 

if __name__ == "__main__": 

    lst = A() 
    while True: 
     cmd = input("Enter an option: ") 
     if cmd.lower() == 'quit': 
      break 
     else: 
      lst.command(cmd) 

print('thanks bye!!') 

将quit操作与其他应用程序命令分离通常是很好的做法。你的A类不需要知道应用程序的退出机制(因此可以在具有不同退出机制的其他应用程序中重用)。

我也使它不会区分大小写。所以quit,QuitQUIT都会触发该动作。