Olg*_*ga 5 python coding-style function python-3.x
假设我们定义一个函数,然后用以下结尾:
def function():
# ...
return result
# To see the result, we need to type:
print(function())
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用以下方式结束函数print
:
def function():
# ...
print(result)
# no need of print at the call anymore so
function()
Run Code Online (Sandbox Code Playgroud)
问题:我return
是否可以通过声明结束功能,通过function()
或不通过?
我的意思是我不关心函数是否保存结果.但是该函数可以有几个不同的结果,即我需要在某个时刻退出循环.主要思想是在屏幕上获得输出.
所以,请让我知道我的变体是否正常,或者它不是'优雅'编码.谢谢!
Tim*_*ker 10
如果你return print(result)
,你基本上是return None
因为print()
回报None
.所以这没有多大意义.
我会说它更干净,return result
并让呼叫者决定是否使用print()
它或做任何其他事情.
在最清洁的方法是使用return
的语句.通常,函数返回一个结果,然后可以通过另一个算法处理该结果.也许你不需要在你的情况下得到一个变量的结果,但想象你在一周,一个月做...
最好的方法是委托print
主程序本身.您将更轻松地管理程序中的数据,正如我所说,您可以链接功能.
想象一下两个函数a(arg)
并b(arg)
返回两个计算.使用函数中的print
语句b
,您将无法执行此操作:
a(b(10))
Run Code Online (Sandbox Code Playgroud)
因为a
将None
在参数中接收一个值(因为函数None
默认返回,最后是print
语句的情况).
TL; DR:大部分时间都遵循这种模式:
def get_full_name(arg1, arg2, ...):
# Do cool stuff
return res # <- result of the function
print get_full_name('foo', 'bar')
full_name = get_full_name('Maxime', 'Lorant')
print some_other_function(full_name)
# etc.
Run Code Online (Sandbox Code Playgroud)