日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

wrist friendly dictionary (Python recipe)

 dinghj 2014-04-24

wrist friendly dictionary (Python recipe)

5

this dictionary allows easy manual creation of nested hierarchies, like so:

window.style.width=5

or...

window['background-color'].rgb= 255,255,255

Python, 13 lines
Copy to clipboard
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class easyaccessdict(dict):
    def __getattr__(self,name):
        if name in self:
            return self[name]
        n=easyaccessdict()
        super().__setitem__(name, n)
        return n
    def __getitem__(self,name):
        if name not in self:
            super().__setitem__(name,nicedict())
        return super().__getitem__(name)
    def __setattr__(self,name,value):
        super().__setitem__(name,value)

By example:

>>> d= easyaccessdict()
>>> d
{}
>>> d.foo.bar= 'a'
>>> d
{'foo':{'bar':'a'}}
>>> d['foo']
{'bar':'a'}
>>> d['foo'].blah= 7
>>> d
{'foo':{'bar':'a', 'blah':7}}
>>> d.a.b.c.e.e.f.g.h= 11

etc.

Share

1 comment

Nezar Abdennur 8 months ago

Note that you can make this even terser by implementing __missing__:

class easyaccessdict(dict):
    def __getattr__(self, name):
        return self[name]
    def __setattr__(self, name, value):
        super().__setitem__(name,value)
    def __missing__(self, name):
        super().__setitem__(name, easyaccessdict())
        return super().__getitem__(name)

Also, super should be called using super(easyaccessdict, self) for this to work in python 2.

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多