测试,如果所有对象都具有相同的成员值

问题描述:

有一个简单的类:测试,如果所有对象都具有相同的成员值

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等),而不必重新编写我的测试逻辑是什么?我能想到的方式通过直方图来做到这一点,但我想有一个“Python化”的方式来做到这一点。

只是比较与第一项的类型每个对象,使用all()功能:

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

不会有任何IndexError如果列表是空的,太。

all()短路,因此,如果一个对象是不相同的类型,另外,紧接在循环场所及返回False。

你可以使用一个itertools recipe for this: all_equal(原始拷贝):

from itertools import groupby 

def all_equal(iterable): 
    "Returns True if all the elements are equal to each other" 
    g = groupby(iterable) 
    return next(g, True) and not next(g, False) 

然后,你可以与访问theType属性生成器表达式称之为:

>>> allThings = [simple('B', 1), simple('B', 2), simple('B', 3), simple('B', 4), simple('B', 5)] 
>>> all_equal(inst.theType for inst in allThings) 
True 

>>> allThings = [simple('A', 1), simple('B', 2), simple('B', 3), simple('B', 4), simple('B', 5)] 
>>> all_equal(inst.theType for inst in allThings) 
False 

鉴于它实际上是把作为配方Python文档中好像它可能是最好的(或至少推荐)的方式来解决这类问题之一。