根据 PEP8,从方法返回值的推荐方式是什么?为什么?我尝试在 PEP8 中查找关于此的文档,但找不到任何内容。
方法一
def method():
a = meth2()
return a
方法二
def method():
return meth2()
最佳答案
PEP8没有指定您是否应该返回变量还是函数。
但是,它确实说你应该保持一致:
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None , and an explicit return statement should be present at the end of the function (if reachable).
# Yes
def myfunction(a: int, b: int) -> int:
if a % 2 == 0:
return int(a ** b)
else:
return 0
# No
def my_bad_function(a: int, b: int) -> int:
if a % 2 == 0:
return int(a ** b)
# Implicitly returns None when the above if statement evaluates False
返回相同类型的变量也是一个好主意(尽管未在 PEP8 中涵盖)。
您会看到我在上述函数中添加了可选的类型提示。第二个函数偶尔会返回 None
。
如果另一个使用此函数的代码块期望返回值具有与 int
相同的属性,例如 int.bit_length()
会导致异常的代码示例:
for n in range(1, 10):
nlen = my_bad_function(n * 5, n).bit_length()
关于python - PEP8 是否建议从方法返回变量或函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41631822/