我想使用括號表達式來訪問dict
中的值,但沒有任何其他dict
功能。重複使用字典的功能是pythonic,但不適用於類似字典的功能?
在下面的示例中,我使用表達式variable[something]
以與dict
相同的方式查詢variable
。 dict
後面沒有其他功能,計算返回的是什麼(something
爲'color'
或"hello"
)。
import random
class ColDict(dict):
def __init__(self, *args):
dict.__init__(self, args)
self.colors = ['blue', 'white', 'red']
def __getitem__(self, item):
if item == 'color':
random.shuffle(self.colors)
return(self.colors[0])
else:
return("hello")
if __name__ == "__main__":
col = ColDict()
print(col['color'], col['color'], col['something']) # red white hello (changes on each call)
此代碼按預期工作。
我想了解的是dict功能(支架調用)的重用是py pyonic,還是最後可以接受。
注意:我明白,這可以通過其他方式來實現(liek一個函數),但我特別重複使用方括號調用。 重複使用,不濫用(這是我的問題的核心)
我看不出你爲什麼要讓這個類從'dict'派生出來。那是什麼給你買的? –
@JohnZwinck:使用括號呼叫的能力。 – WoJ
這個問題很基於觀點。 ***在我看來*** –