如何优雅地忽略 Python 函数的一些返回值? [英] How to elegantly ignore some return values of a Python function?

查看:46
本文介绍了如何优雅地忽略 Python 函数的一些返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时函数会提供一个返回值,您只想丢弃该值而不是发送到输出流.处理这个问题的优雅方式是什么?

Sometimes a function gives a return value which you'd just want to discard rather than send to the output stream. What would be the elegant way to handle this?

请注意,我们讨论的是一个函数,该函数返回一些您无法更改的内容.

Note that we're talking about a function that returns something which you cannot change.

def fn():
    return 5

我个人以前使用过 null,但我正在寻找一种更 Pythonic 的方式:

I personally have used null before, but I'm looking for a more pythonic way:

null = fn()

推荐答案

显示这一点的标准方法是将您不想要的结果分配给 _.例如,如果一个函数返回两个值,但您只想要第一个,请执行以下操作:

The standard way to show this is to assign the results you don't want to _. For instance, if a function returns two values but you only want the first, do this:

value, _ = myfunction(param)

大多数 Python linter 会识别使用 _ 而不会抱怨未使用的变量.

Most Python linters will recognize the use of _ and not complain about unused variables.

如果你想忽略所有的返回值,那么就不要赋值给任何东西;除非你告诉它,否则 Python 不会对结果做任何事情.打印结果只是 Python shell 中的一项功能.

If you want to ignore all returns, then simply don't assign to anything; Python doesn't do anything with the result unless you tell it to. Printing the result is a feature in the Python shell only.

这篇关于如何优雅地忽略 Python 函数的一些返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆