python - 重用 dict 的特征而不是类似 dict 的特征是 pythonic 吗?

标签 python class dictionary

我想使用括号表达式来访问 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)

read more about it

关于python - 重用 dict 的特征而不是类似 dict 的特征是 pythonic 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40693167/

相关文章:

Java OOP 公共(public)、私有(private)、 protected

java - 在 Java 中,像 "int"这样的原始数据类型是一个类还是一个对象?

python - 在 python tkinter 中设置滚动条位置的正确方法

python - 如何在不重新启动 Pylons 的情况下重新加载修改后的文件?

python - 如何将 int 转换为以 9 为基数且不含 0 的 int?

c++ - 对象映射的 vector

javascript - openlayers3移动功能,3.14以上版本不起作用

Python:在将每一行与矩阵中的每一行进行比较后存储非零唯一行的索引

java - 扫雷程序中的 NullPointerException

java - 需要 Delayed 和 Map 的混合