gpt4 book ai didi

python - 将参数限制为 python 中的特定值

转载 作者:太空狗 更新时间:2023-10-29 21:31:45 25 4
gpt4 key购买 nike

如果我有一个带有字符串参数的 python 函数,它需要在特定的值列表中,处理这个问题的最佳方法是什么?是否有在文档字符串或其他内容中表达这一点的约定?

例如。

def makeShape(shape):
assert shape in ["circle", "square", "triangle"]

有没有更好的方式来表达形状应该始终是这三个值之一?

最佳答案

您可以使用 enum 来正确排序形状:

class rightShape(Enum):
circle = 1
square = 2
triangle = 3

def makeShape(rightShape):
# code in function

如果您尝试向函数传递除 circlesquaretriangle 之外的任何内容,这将抛出一个诚实至善的错误.

关于python - 将参数限制为 python 中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22418088/

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