@dataclass
class Component:
name: str
class Assembly:
def __init__():
names = ["Able", "Baker", "Charlie"]
self.components = [Component(name) for name in names]
def test_assembly():
"""Assembly should be initialised with three Components"""
assembly = Assembly()
assert assembly.components == [Component] * 3 # doesn't work
斷言不起作用,因為它將類實體串列 ( assembly.components) 與型別別串列進行比較。有沒有寫這個測驗的好方法?
uj5u.com熱心網友回復:
您可以使用 map() 將 assembly.components 中的所有元素轉換為型別,然后您可以將映射轉換為串列并使用 list.count 函式查看該型別在串列中出現的次數。像這樣的東西:
assert list(map(type,assembly.components)).count(Component) == 3
如果 assembly.components 中的每個專案都已經是一個型別,您可以確保它是一個串列,然后像這樣立即使用 list.count 函式:
assert list(assembly.components).count(Component) == 3
編輯:另外,如果你發現自己在迭代任何東西并想要比較模式出現的次數,我相信使用 int 變數并為你找到的每個模式增加它要好得多,而不是你正在做的完全創建新的串列并比較它們,大量的會減慢速度。(增量方法是我 bleieve .count 函式的作業方式,因此在可能的情況下嘗試使用它。)
uj5u.com熱心網友回復:
您可以遍歷串列并使用isinstance():
def count_instance(lst, cls):
count = 0
for i in lst:
if isinstance(i, cls):
count = 1
return count
assert count_instance(assembly.components, Component) == 3
uj5u.com熱心網友回復:
assert [type(comp) for comp in assembly.components] == [Component] * 3
這可以完成作業 - 但我懷疑可能有更好的解決方案?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/402987.html
標籤:
下一篇:字串到python中的單個位元組
