Python函数知道请求多少个输出?(Do Python functions know how many outputs are requested? [duplicate])

编程入门 行业动态 更新时间:2024-10-18 01:27:26
Python函数知道请求多少个输出?(Do Python functions know how many outputs are requested? [duplicate])

这个问题在这里已经有了答案:

nargout在Python 4中的答案

在Python中,函数是否知道请求了多少输出? 例如,我可以有一个函数,通常返回一个输出,但如果请求两个输出,它会做一个额外的计算并返回呢?

或者这不是标准的做法吗? 在这种情况下,最好避免提供第二个输入的额外函数参数。 但我有兴趣学习这样做的标准方法。

This question already has an answer here:

nargout in Python 5 answers

In Python, do functions know how many outputs are requested? For instance, could I have a function that normally returns one output, but if two outputs are requested, it does an additional calculation and returns that too?

Or is this not the standard way to do it? In this case, it would be nice to avoid an extra function argument that says to provide a second input. But I'm interested in learning the standard way to do this.

最满意答案

真实而简单的答案是:没有。

Python函数/方法不知道请求了多少输出,因为在函数调用之后解包返回的元组。

但是,最好的做法是使用下划线(_)作为不需要时从函数返回的未使用参数的占位符,例如:

def f(): return 1, 2, 3 a, b, c = f() # if you want to use all a, _, _ = f() # use only first element in the returned tuple, 'a' _, b, _ = f() # use only 'b'

例如,当使用下划线(_)时,pylint将会禁止任何未使用的参数警告。

The real and easy answer is: No.

Python functions/methods does not know about how many outputs are requested, as unpacking of a returned tuple happens after the function call.

What's quite a best practice to do though is to use underscore (_) as a placeholder for unused args that are returned from functions when they're not needed, example:

def f(): return 1, 2, 3 a, b, c = f() # if you want to use all a, _, _ = f() # use only first element in the returned tuple, 'a' _, b, _ = f() # use only 'b'

For example, when using underscore (_) pylint will suppress any unused argument warnings.

更多推荐

本文发布于:2023-08-01 12:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1358014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多少个   函数   Python   functions   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!