有人会告诉我内置函数exit()和quit()之间有什么区别.
如果我错了,请纠正我.我试过检查它,但我没有得到任何东西.
1)当我为每一个使用help()和type()函数时,它表示两者都是类Quitter的对象,它在模块中定义site.
2)当我使用id()检查每个地址时,它返回不同的地址,即这些是同一类的两个不同的对象site.Quitter.
>>> id(exit)
13448048
>>> id(quit)
13447984
Run Code Online (Sandbox Code Playgroud)
3)由于地址在后续调用中保持不变,即每次都不使用返回包装器.
>>> id(exit)
13448048
>>> id(quit)
13447984
Run Code Online (Sandbox Code Playgroud)
是否有人会向我提供有关这两者之间差异的详细信息,如果两者都做同样的事情,为什么我们需要两个不同的功能.
Mik*_*kin 15
简短的回答是:exit()和quit()都是同一个Quitter类的实例,区别在于仅命名,必须添加它以增加解释器的用户友好性.
有关详细信息,请查看源代码: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')
Run Code Online (Sandbox Code Playgroud)
我们在python-3.x中看到的逻辑相同.