试图实现一个只获取特定对象列表的函数,但似乎无法实现它
假设我们有一个功能测试:
def testing(myTypes=None):
if myTypes:
if isinstance(myTypes, list) and all([isinstance(item, myType) for item in myTypes]):
print("Correct")
else:
print("myTypes must be a list of myType object only")
else:
print("No myTypes provided")
class myType:
a = "a"
b = "b"
c = "c"
testing()
testing(['xd'])
testing([myType.a, myType.b])
输出为:
No myTypes provided
myTypes must be a list of myType object only
myTypes must be a list of myType object only
但我希望最后一个的输出为“Correct”。是的,我知道我最终会在参数中发送一个字符串,因此它不是一个myType
对象,但似乎无法理解应该如何做
所以有两个问题:
myTypes
中提供的所有字符串是否都存在于该字符串集中是很容易的,但是用户需要知道这个列表,可能会出现拼写错误,拥有一个类(imo)更容易李>
您需要将} :
myType
更改为^{我现在得到这个输出:
用
myType
作为Enum
,myType.a
现在不同于"a"
。这导致您的第二个示例仍然失败,但您的第三个示例现在是正确的。Enum
还表示一组强类型的固定值,这是“将某些有效字符串限制为有效选项”的完美用例请注意,您应该将
myType
重命名为MyType
,并将a
、b
和c
大写。这是Enum
的惯例相关问题 更多 >
编程相关推荐