gpt4 book ai didi

python - 有没有办法获取函数的返回值并同时测试它是 "nonzero"?

转载 作者:行者123 更新时间:2023-11-28 20:09:39 25 4
gpt4 key购买 nike

我有这样的代码:

if(func_cliche_start(line)):
a=func_cliche_start(line)
#... do stuff with 'a' and line here
elif(func_test_start(line)):
a=func_test_start(line)
#... do stuff with a and line here
elif(func_macro_start(line)):
a=func_macro_start(line)
#... do stuff with a and line here
...

每个 func_blah_start 函数要么返回 None 要么返回一个字符串(基于输入行)。我不喜欢对 func_blah_start 的冗余调用,因为它看起来很浪费(func_blah_start 是“纯”的,所以我们可以假设没有副作用)。对于这类事情,有没有更好的成语,或者有更好的方法吗?

也许我错了,(我的 C 已经生锈了),但我认为你可以在 C 中做一些事情:

int a;
if(a=myfunc(input)){ /*do something with a and input here*/ }

有对应的 python 吗?

最佳答案

为什么不在 if 语句之前将函数 func_cliche_start 赋值给变量 a?

a = func_cliche_start(line)
if a:
pass # do stuff with 'a' and line here

如果 func_cliche_start(line) 返回 None,则 if 语句将失败。

关于python - 有没有办法获取函数的返回值并同时测试它是 "nonzero"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com