问题
I am getting very weird interpreter behaviour:
>>> _
True
>>> type(True)
<class 'bool'>
>>> type(_)
<class 'bool'>
I tried this because _ came up as a suggestion in Bpython, but it seems to work in the normal interpreter too. I am using
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Can anybody explain why _ is a substitute for True? Is it legacy, similarly to how ";" can be used to end commands, but is not necessary/encouraged?
EDIT: It seems to be random. This does not happen in a new terminal, but once I start working on something _ starts becoming true. What the hell is going on?
回答1:
_
will be the result of the last evaluated command - at interpreter start up there isn't any so you'll get a NameError
... after that, you'll get the previous result... Try opening a new interpreter and doing 2 + 2
... you'll see 4
returned, then type _
... eg:
>>> _
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
_
NameError: name '_' is not defined
>>> 2 + 2
4
>>> _
4
回答2:
2 + 1
Out[19]: 3
_ + 3
Out[20]: 6
_
stores the last returned value. Try it out.
回答3:
_
simply gives you the last result evaluated (in the REPL, not in an ordinary script). This can also mysteriously prevent objects from being deleted immediately.
回答4:
_ in the interactive interperter is usually the last output you received.
>>> 1 + 1
2
>>> _
2
Note it only applies to outputs (printed data won't do).
来源:https://stackoverflow.com/questions/22269897/why-does-typing-in-the-python-interpreter-return-true