[英]How can I accept only some strings in Python function?
I want to make it like this:我想让它像这样:
>>> myfunc("strawberry")
ok
# myfunc only works with strawberry
I know that most people will answer with:我知道大多数人会回答:
def myfunc(something):
if something == "strawberry":
print("ok")
But I want to do all this in the parameter setting.但我想在参数设置中完成这一切。
Like, kind of like this:就像,有点像这样:
def myfunc(something: OnlyThese["strawberry", "cake"]:
print("ok")
Although the code above is very incorrect, I want to see if Python already has a feature like this.虽然上面的代码很不正确,但是我想看看Python是否已经有这样的功能。
Don't believe there is a way to do what you are wanting to do without writing code in the function body.不要相信没有在 function 主体中编写代码的情况下可以做你想做的事情。
I found answers to a similar question at我在以下位置找到了类似问题的答案
enforce arguments to a specific list of values 将 arguments 强制执行到特定的值列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.