gpt4 book ai didi

python - 如何设置可选参数?

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:17 25 4
gpt4 key购买 nike

请帮忙,我的代码中有这个功能,将来会成为一个模块。到目前为止我还没有完成模块,但我想允许用户将匹配 boolean 值更改为 False,但我不想强制他们填写它以防他们想保持它为真因此,如果只需要 1 个输入但第二个 (match = False) 可选,我会很高兴。它是根据邮政编码字典返回邮政编码或城市名称的模块。

def returnCode(city):
cityOriginal = city
city = str(city)
match = True
if match:
city = get_close_matches(city, codes.values())[0]
if hasNumbers(city) == True and hasNumbers(cityOriginal) == False:
city = sub('[0123456789]', '1', city)
return cityDict[city]

returnCode('Berlin')
#returnCode('Berlin', match=False) ... how to?

最佳答案

您可以在 Python 中为参数指定默认值,在调用函数时可以使用显式参数覆盖该默认值。

def returnCode(city, match=True):
cityOriginal = city
city = str(city)
if match:
city = get_close_matches(city, codes.values())[0]
if hasNumbers(city) == True and hasNumbers(cityOriginal) == False:
city = sub('[0123456789]', '1', city)
return cityDict[city]

returnCode('Berlin')
returnCode('Berlin', match=False) # these will both run just fine

这实际上就是您所需要的,您非常接近 :) 如果未指定匹配,它将默认为 True,否则可以由调用者选择设置。

关于python - 如何设置可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53180033/

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