gpt4 book ai didi

python - 是否可以在函数参数中隐式使用 bool 真值?

转载 作者:行者123 更新时间:2023-12-01 08:23:12 25 4
gpt4 key购买 nike

在大多数语言中,包括 Python,变量的真实值可以在条件表达式中隐式使用,即:

    is_selected = True
If is_selected:
#do something

是否可以创建其参数行为类似的函数?例如,如果我有一个名为 asort 的排序函数,它接受参数 ascending调用它的标准方法是:

    asort(list, ascending=True)

我设想的是调用如下函数:

    asort(list, ascending)

编辑:我正在寻找的行为与默认参数略有不同。也许排序是一个不好的例子,但让我们继续讨论,假设我的 asort 函数对于升序参数有一个 default=False

def asort(list, ascending=False):
if ascending: #no need to =True here
#sort ascending
Else:
#sort descending

如果我想升序排序,我必须使用asort(alist, ascending=True)我想知道是否有一种方法可以将非默认升序调用为asort(alist, ascending)

最佳答案

是的,您可以使用默认参数定义函数:

def f(a=True, b=False, c=1):
print(a,b,c);

f() # True False 1
f(a=False) # False False 1
f(a=False, c=2) # False False 2

关于python - 是否可以在函数参数中隐式使用 bool 真值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485521/

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