python中退出和退出之间的区别

时间:2013-10-10 06:35:59

标签: python-2.7

有人会告诉我内置函数exit()和quit()之间有什么区别。

如果我在任何时候错了,请纠正我。我试过检查它,但我没有得到任何东西。

1)当我为每一个使用help()和type()函数时,它表示两者都是类Quitter的对象,它在模块site中定义。

2)当我使用id()检查每个地址时,它返回不同的地址,即这些是同一类site.Quitter的两个不同对象。

>>> id(exit)
13448048
>>> id(quit)
13447984

3)并且由于地址在后续调用中保持不变,即每次都不使用返回包装器。

>>> id(exit)
13448048
>>> id(quit)
13447984

有人会向我提供有关这两者之间差异的详细信息,如果两者都做同样的事情,为什么我们需要两种不同的功能。

1 个答案:

答案 0 :(得分:12)

简短答案退出()退出()是同一 Quitter 的实例class,不同之处仅在于命名,必须添加以增加解释器的用户友好性。

有关详细信息,请查看来源:http://hg.python.org/cpython

Lib/site.py (python-2.7)中,我们看到以下内容:

def setquit():
    """Define new builtins 'quit' and 'exit'.

    These are objects which make the interpreter exit when called.
    The repr of each object contains a hint at how it works.

    """
    if os.sep == ':':
        eof = 'Cmd-Q'
    elif os.sep == '\\':
        eof = 'Ctrl-Z plus Return'
    else:
        eof = 'Ctrl-D (i.e. EOF)'

    class Quitter(object):
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            return 'Use %s() or %s to exit' % (self.name, eof)
        def __call__(self, code=None):
            # Shells like IDLE catch the SystemExit, but listen when their
            # stdin wrapper is closed.
            try:
                sys.stdin.close()
            except:
                pass
            raise SystemExit(code)
    __builtin__.quit = Quitter('quit')
    __builtin__.exit = Quitter('exit')

我们在python-3.x中看到的逻辑相同。

相关问题