![](/img/trans.png)
[英]How to check if 2 class objects have same parameters inside a list in python?
[英]Python check parameters is a list of a certain objects
试图实现一个函数来只获取某些对象的列表,但似乎无法实现它。
所以假设我们有一个功能测试:
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
但我希望最后一个输出“正确”。 是的,我知道我最终会在参数中发送一个字符串,因此它不是myType
对象,但似乎无法弄清楚应该如何完成。
所以两个问题:
myTypes
提供的所有字符串是否都存在于该组中会很容易,但是用户需要知道这个列表,可能会出现拼写错误,并且更容易拥有一个类(海事组织)。您需要将myType
更改为Enum
:
from enum import Enum
class myType(Enum):
a = "a"
b = "b"
c = "c"
我现在得到这个输出:
No myTypes provided
myTypes must be a list of myType object only
Correct
将myType
作为Enum
, myType.a
现在与"a"
不同。 这会导致您的第二个示例仍然失败,但您的第三个示例现在将是正确的。 Enum
还表示一组强类型的固定值,这是“将某些有效字符串限制为有效选项”的完美用例。
请注意,您应该将myType
重命名为MyType
并将a
、 b
和c
大写。 这是Enum
的约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.