在Python函数返回中使用括号的最佳实践? [英] Best practice for using parentheses in Python function returns?

查看:58
本文介绍了在Python函数返回中使用括号的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python,到目前为止,我绝对喜欢它.关于它的一切.

I'm learning Python and, so far, I absolutely love it. Everything about it.

我只想问一个关于函数返回中似乎不一致的问题,我有兴趣学习规则背后的逻辑.

I just have one question about a seeming inconsistency in function returns, and I'm interested in learning the logic behind the rule.

如果我在函数返回中返回文字或变量,则不需要括号:

If I'm returning a literal or variable in a function return, no parentheses are needed:

def fun_with_functions(a, b):
    total = a + b
    return total

但是,当我返回另一个函数调用的结果时,该函数被包装在一组括号内.发挥作用:

However, when I'm returning the result of another function call, the function is wrapped around a set of parentheses. To wit:

 def lets_have_fun():
     return(fun_with_functions(42, 9000))

至少,这是使用此处(跳至练习10)进行在线练习.

This is, at least, the way I've been taught, using the A Smarter Way to Learn Python book. I came across this discrepancy and it was given without an explanation. You can see the online exercise here (skip to Exercize 10).

有人可以向我解释为什么这样做是必要的吗?首先是否有必要?我还应该注意括号语法中的其他类似变化吗?

Can someone explain to me why this is necessary? Is it even necessary in the first place? And are there other similar variations in parenthetical syntax that I should be aware of?

我将问题的标题改写为反映答案.就像我最初想的那样,在圆括号内返回结果不是强制性的,但据我所知,它通常被认为是最佳实践.

推荐答案

这不是必需的.括号的使用有多种原因,一种是出于代码风格的原因:

It's not necessary. The parentheses are used for several reason, one reason it's for code style:

示例= some_really_long_function_name()或another_really_function_name()

因此您可以使用:

example = (some_really_long_function_name()
           or
           another_really_function_name())

另一种用法类似于数学,用于强制评估.因此,您要确保括号之间的先后顺序.我想函数会返回另一个函数的结果,这是确保第一个函数执行的最佳实践,但这不是必需的.

Another use it's like in maths, to force evaluation precede. So you want to ensure the excute between parenthese before. I imagine that the functions return the result of another one, it's just best practice to ensure the execution of the first one but it's no necessary.

这篇关于在Python函数返回中使用括号的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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