我想使用括号表达式来访问 dict
中的值,但没有任何其他 dict
功能。
在下面的示例中,我使用表达式 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 功能(括号调用)的重用是 pythonic 还是最终可以接受。
注意:我知道这可以通过其他方式(例如函数)来完成,但我特别喜欢重用括号调用。 重用,而不是滥用(这是我问题的核心)
最佳答案
如果您不需要 dict 的任何功能,只需提供 __getitem__()
import random
class ColDict:
def __init__(self, *args):
self.colors = ['blue', 'white', 'red']
def __getitem__(self, item):
if item == 'color':
return random.choice(self.colors)
else:
return("hello")
if __name__ == "__main__":
col = ColDict()
print(col['color'], col['color'], col['something']) # red white hello (changes on each call)
关于python - 重用 dict 的特征而不是类似 dict 的特征是 pythonic 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40693167/