gpt4 book ai didi

python - 测试所有对象是否具有相同的成员值

转载 作者:太空狗 更新时间:2023-10-29 11:35:31 26 4
gpt4 key购买 nike

我在 中有一个简单的类:

class simple(object):
def __init__(self, theType, someNum):
self.theType = theType
self.someNum = someNum

稍后在我的程序中,我创建了这个类的多个实例,即:

a = simple('A', 1)
b = simple('A', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('C', 5)

allThings = [a, b, c, d, e] # Fails "areAllOfSameType(allThings)" check

a = simple('B', 1)
b = simple('B', 2)
c = simple('B', 3)
d = simple('B', 4)
e = simple('B', 5)

allThings = [a, b, c, d, e] # Passes "areAllOfSameType(allThings)" check

我需要测试 allThings 中的所有元素是否都具有相同的 simple.theType 值。我将如何为此编写通用测试,以便将来可以包含新的“类型”(即 DEF等)而不必重新编写我的测试逻辑?我可以想出一种通过直方图来执行此操作的方法,但我认为有一种“pythonic”方法可以执行此操作。

最佳答案

只需将每个对象与第一个项目的类型进行比较,使用 all()功能:

all(obj.theType == allThings[0].theType for obj in allThings)

如果列表为空,也不会出现IndexError

all() 短路,因此如果一个对象与另一个对象的类型不同,循环会立即中断并返回 False

关于python - 测试所有对象是否具有相同的成员值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45950096/

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