2017-08-30 76 views
2

有一個簡單的類:測試,如果所有對象都具有相同的成員值

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化」的方式來做到這一點。

回答

3

只是比較與第一項的類型每個對象,使用all()功能:

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

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

all()短路,因此,如果一個對象是不相同的類型,另外,緊接在循環場所及返回False。

2

你可以使用一個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文檔中好像它可能是最好的(或至少推薦)的方式來解決這類問題之一。

相關問題