In python, what the underline parameter mean in function

前端 未结 3 1278
长发绾君心
长发绾君心 2020-12-30 05:12

For example, I read a code:

def parse_doc(self, _, doc):

What does the underline \"_\" mean?

3条回答
  •  天涯浪人
    2020-12-30 06:01

    It usually is a place holder for a variable we don't care about. For instance if you have a for-loop and you don't care about the value of the index, you can do something like

    for _ in xrange(10):
       print "hello World." # just want the message 10 times, no need for index val
    

    another example, if a function returns a tuple and you don't care about one of the values you could use _ to make this explicit. E.g.,

    val, _ = funky_func() # "ignore" one of the return values
    

    Aside

    Unrelated to the use of '_' in OP's question, but still neat/useful. In the Python shell, '_' will contain the result of the last operation. E.g.,

    >>> 55+4
    59
    >>> _
    59
    >>> 3 * _
    177
    >>>
    

提交回复
热议问题