Accessing dict keys like an attribute?

前端 未结 27 2539
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  一个人的身影
    2020-11-22 04:57

    How about Prodict, the little Python class that I wrote to rule them all:)

    Plus, you get auto code completion, recursive object instantiations and auto type conversion!

    You can do exactly what you asked for:

    p = Prodict()
    p.foo = 1
    p.bar = "baz"
    

    Example 1: Type hinting

    class Country(Prodict):
        name: str
        population: int
    
    turkey = Country()
    turkey.name = 'Turkey'
    turkey.population = 79814871
    

    auto code complete

    Example 2: Auto type conversion

    germany = Country(name='Germany', population='82175700', flag_colors=['black', 'red', 'yellow'])
    
    print(germany.population)  # 82175700
    print(type(germany.population))  # 
    
    print(germany.flag_colors)  # ['black', 'red', 'yellow']
    print(type(germany.flag_colors))  # 
    

提交回复
热议问题