Python 函数可选参数 - 可以添加为条件吗? [英] Python function optional arguments - possible to add as condition?

查看:23
本文介绍了Python 函数可选参数 - 可以添加为条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以某种方式将条件语句分配给可选参数?

Is it possible, somehow, to aassign a condtional statement toan optional argument?

我最初尝试使用以下结构没有成功:

My initial attempts, using the following construct, have been unsuccessful:

y = {some value} if x == {someValue} else {anotherValue}

x 预先分配的位置.

更具体地说,我希望我的函数签名看起来像:

More specifically, I want my function signature to look something like:

def x(a, b = 'a' if someModule.someFunction() else someModule.someOtherFunction()):
   :
   :

非常感谢

推荐答案

当然,您就是这样做的.您可能需要记住,b 的默认值将在您定义函数后立即设置,这可能并不理想:

Sure, that's exactly how you do it. You may want to keep in mind that b's default value will be set immediately after you define the function, which may not be desirable:

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 作为占位符的详细方式更容易理解:

Just because this is possible doesn't mean that you should do it. I wouldn't, at least. The verbose way with using None as a placeholder is easier to understand:

def foo(b=None):
    if b is None:
        b = 5 if test() else 10

    print b

这篇关于Python 函数可选参数 - 可以添加为条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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