2012年6月21日 星期四

_ 在python程式碼中所代表的意義


In the standard Python REPL, _ represents the last returned value -- at the point where you calledlen(_)_ was the value 'abc'.
For example:
>>> 10
10
>>> _10
>>> _ + 5
15
>>> _ + 5
20
Note that there is no such functionality within Python scripts. In a script, _ is just your run-of-the-mill identifier.
Also, beware of reassigning _ in the REPL if you want to use it like above!
>>> _ = "underscore"
>>> 10
10
>>> _ + 5
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    _ + 5
TypeError: cannot concatenate 'str' and 'int' objects
To undo the assignment (and remove the _ from globals), you'll have to:
>>> del _
then the functionality will be back to normal (the __builtin__._ will be visible again).

沒有留言:

張貼留言