这个问题在这里已经有了答案:
nargout在Python 4中的答案在Python中,函数是否知道请求了多少输出? 例如,我可以有一个函数,通常返回一个输出,但如果请求两个输出,它会做一个额外的计算并返回呢?
或者这不是标准的做法吗? 在这种情况下,最好避免提供第二个输入的额外函数参数。 但我有兴趣学习这样做的标准方法。
This question already has an answer here:
nargout in Python 5 answersIn 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.
更多推荐
发布评论