重复使用dict的功能是pythonic,而不是类似dict的功能吗?

WoJ*_*WoJ 2 python dictionary class

我想使用用于访问a中的值的括号表达式dict,但没有任何其他dict功能.

在下面的示例中,我使用表达式variable[something]variable与a相同的方式进行查询dict.这里有没有其他的功能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)
Run Code Online (Sandbox Code Playgroud)

此代码按预期工作.

我想要理解的是dict功能(括号调用)的重用是否是pythonic,或者最后是否可以接受.

注意:我知道这可以通过其他方式(使用函数)来完成,但我特别注意重用括号调用.重用,而不是滥用(这是我的问题的核心)

dah*_*ens 5

如果您不需要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)
Run Code Online (Sandbox Code Playgroud)

阅读更多相关信息