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

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

问题描述

是否有可能,不知何故,到aassign一个condtional声明TOAN可选参数?

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已经事先分配的。

where x has assigned beforehand.

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

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

正因为这是可能的,并不意味着你应该这样做。我不会,至少。使用无冗长的方式作为占位符是比较容易理解:

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天全站免登陆