是否可以以某种方式将条件语句分配给可选参数?
我最初的尝试使用以下结构,但没有成功:
y = {some value} if x == {someValue} else {anotherValue}
其中 x 已预先分配。
更具体地说,我希望我的函数签名看起来像:
def x(a, b = 'a' if someModule.someFunction() else someModule.someOtherFunction()):
:
:
非常感谢
当然,你就是这样做的。您可能需要记住这一点b
的默认值将在定义函数后立即设置,这可能是不可取的:
def test():
print("I'm called only once")
return False
def foo(b=5 if test() else 10):
print(b)
foo()
foo()
和输出:
I'm called only once
10
10
仅仅因为这是可能的并不意味着您应该这样做。至少我不会。使用的详细方式None
作为占位符更容易理解:
def foo(b=None):
if b is None:
b = 5 if test() else 10
print b
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)